在UITableView中点击单元格时更改单元格的颜色

时间:2011-11-10 04:27:58

标签: iphone objective-c xcode uitableview

我在我的应用程序中使用UITableView,并且我在文件DealsCC.xib中创建了自定义单元格,当单元格被点击时,单元格的颜色应该更改为蓝色,但在我的代码中不会发生。我按如下方式编写代码:

static NSString *MyIdentifier = @"dealsCC";
    dealsCC *cell = (dealsCC *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    [cell selectionStyle:UITableViewCellSelectionStyleBlue];

我想在行

中提及
[cell selectionStyle:UITableViewCellSelectionStyleBlue];

警告消息存在且是“dealsCC可能不响应-selectionStyle”

请帮助我解决这个问题 提前完成。

3 个答案:

答案 0 :(得分:1)

请参阅以下stackoverflow链接,请检查您是否已关注它们 1)link1 2)link2 3)enter link description here

答案 1 :(得分:1)

在表格视图单元格的自定义类中尝试此操作

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
       self.selectionStyle = UITableViewCellSelectionStyleBlue;
       [super setSelected:selected animated:animated];

}

警告是因为方法应该是

[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

而不是[cell selectionStyle:UITableViewCellSelectionStyleBlue];

答案 2 :(得分:0)

使用cell.selectionStyle = UITableViewCellSelectionStyleGray;更改单元格选择的样式。但此处selectionStyle仅输入UITableViewCellSelectionStyle类型。

要更改颜色,您需要使用图像。使用selectedBackgroundView.image属性并关注tutorial Link

或者您也可以尝试

    cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
    cell.selectedBackgroundView.backgroundColor = [UIColor redColor];

修改

好的我正在更新代码以防你在单元格上有任何其他控件,然后你可以尝试下面的代码。

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *CellIdentifier = @"myCellId";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
     UIView *v = [[[UIView alloc] init] autorelease];
     v.backgroundColor = [UIColor redColor]; // any color of your choice.
     cell.selectedBackgroundView = v;
      // After this line add all other controlls you are adding...
     }
// Set up the cell...
cell.textLabel.text = @"foo";
return cell;
}