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;
    }
}

0 件のコメント: