我試圖在我的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