5

UISearchBar があります。セルを選択すると、セル全体に [UIColor grayColor] が必要です。

以下のコードでは、contentView の色がグレーに表示されます。ただし、背景の accessoriesType の色は青色で表示されます。

ここに画像の説明を入力

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     

UITableViewCell *cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor grayColor];

    if (self.lastSelected && (self.lastSelected.row == indexPath.row))
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell setSelected:NO animated:TRUE];
        self.lastSelected = nil;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.accessoryView.backgroundColor = [UIColor grayColor]; // Not working
        [cell setSelected:TRUE animated:TRUE];

        UITableViewCell *old = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:self.lastSelected];
        old.accessoryType = UITableViewCellAccessoryNone;
        [old setSelected:NO animated:TRUE];
        self.lastSelected = indexPath;
    }

青を[UIColor grayColor]としても表示するにはどうすればよいですか?

4

1 に答える 1

10

セル ビューの一部にすぎないコンテンツ ビューの背景色を変更しています。

UITableViewCell 表現

セル全体の背景色を変更します。ただし、ここでtableView:didDeselectRowAtIndexPath:説明されているように機能しないため、それを行うことはできません。

: セルの背景色を変更する場合 (UIView で宣言された backgroundColor プロパティを介してセルの背景色を設定することにより) 、データ ソースではtableView:willDisplayCell:forRowAtIndexPath:なくデリゲートのメソッドで行う必要があります。tableView:cellForRowAtIndexPath:

tableView:didSelectRowAtIndexPath:あなたの場合、 ivar にインデックスを保存し、テーブル ビューをリロードして、選択した行を追跡します。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    _savedIndex = indexPath;
    [tableView reloadData];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_savedIndex isEqual:indexPath]) {
         cell.backgroundColor = [UIColor grayColor];
    }  
}
于 2013-04-19T20:31:27.770 に答える