2012-07-12

UISearchBarの検索文字に初期値を設定する

UISearchBarで検索を行う場合、通常は検索バーの初期値が空欄で、ユーザが検索文字を入力します。この挙動を変更して、検索文字の初期値に空文字以外を指定できるようにするのは思いのほか大変でした。

問題は、searchResultsTableViewが正しく表示されないことです。searchBar.text = defaultSearchWord; という処理を、searchBarTextDidBeginEditing: 、searchBarShouldBeginEditing: 、searchDisplayControllerWillBeginSearch: などに記述したのですが、これではsearchResultsTableViewが無効で検索も正しく行われませんでした。
searchDisplayControllerDidBeginSearch: でsearchBar.text を設定してやらないとダメでした。

2012-07-11

UITableViewの「結果なし」ラベルを隠す

UISearchTableViewで、検索結果がヒットしない場合に「結果なし」とか「No Result」とかいったラベルが表示されますが、これを隠したかったのでいろいろ調べてみました。

どうやら、この文字列を直接操作するプロパティなどは存在しないようです。
UILabelを探し出して非表示にするという方法が考えられましたが、これはちょっと複雑なことになりそうだったので、表示するデータがないときはダミーの行を表示するというアプローチを試みました。

表示すべきデータがない場合は、0行ではなく、空文字のダミー行が1つだけ存在するということにします。さらに、このダミー行を選択することができないようにします。これで目的は達せられたようです。
だいたい次のようなコードになります。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return MAX(self.dataArray.count, 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* CellIdentifier = @"SearchCandidateCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    if (self.dataArray.count > 0) {
        Data* data = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = data.text;
    }
    else {
        cell.textLabel.text = @"";
    }
    return cell;
}

- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataArray.count > 0) {
        return indexPath;
    }
    else {
        return nil;
    }
}