我试图在我的tableView的右角做一个UIBarButtonItem,以突出显示和取消突出显示单元格时按下。用更少的话来说,当用户按下按钮时,一系列单元格会将它们的背景颜色从白色变为黄色。如何通过点击UIBarButtonItem来获取UITableViewCell更改背景颜色?
虽然我没有做到这一点,因为每当我按下该按钮,应用程序崩溃。
下面是我使用的创建按钮的代码:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *barButton;
barButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"high.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(colorCells:)] autorelease];
self.navigationItem.rightBarButtonItem = barButton;
}
在这里,使它突出的单元格区域:
- (void) colorCells:(id)sender
{
UITableViewCell *cell;
NSString *cellValue = cell.textLabel.text;
if ([cellValue isEqual: @"textTheCellShouldBeEqualTo"]){
cell.backgroundColor = [UIColor colorWithRed:251/255.0f green:255/255.0f blue:192/255.0f alpha:1]; ;
cell.imageView.image = [UIImage imageNamed:@"hot.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
}
我在哪里失败?它应该工作正常。要么?我错过了什么吗?该视图是一个UITableViewController。
编辑
我修改我的代码如下所示:
- (void) colorCells:(id)sender{
UITableViewCell *cell;
NSInteger nSections = [self.tableView numberOfSections];
for (int j=0; j<nSections; j++) {
NSInteger nRows = [self.tableView numberOfRowsInSection:j];
for (int i=0; i<nRows; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:j];
cell = [self.tableView cellForRowAtIndexPath:indexPath];
}
NSString *cellValue = cell.textLabel.text;
if ([cellValue isEqual: @"textTheCellShouldBeEqualTo"]){
cell.backgroundColor = [UIColor colorWithRed:251/255.0f green:255/255.0f blue:192/255.0f alpha:1]; ;
cell.imageView.image = [UIImage imageNamed:@"hot.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
[self.tableView reloadData];
}
}
现在,它不会崩溃,但它没有颜色的背景了。有任何想法吗?
尝试添加[self.tableView beginUpdates];和[self.tableView endUpdates];在末尾 – Novarg 2012-01-11 15:51:03
仍然无法为选定的单元格着色。 :S – Phillip 2012-01-11 15:53:13