多個項目,我有在我試圖放置一個按鈕,圖像和標籤的實現代碼如下。我想要更改按鈕的圖像,一旦點擊。的UITableView在每個單元
下面的代碼:
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
checkedImg = [UIImage imageNamed:@"buttonUnChecked1.png"];
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
//Set up the cell...
NSString *cellValue = [suggestions objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
check = [UIButton buttonWithType:UIButtonTypeCustom];
check.frame=CGRectMake(0,35,20,20);
[check setImage:checkedImg forState:UIControlStateNormal];
[check addTarget:self action:@selector(checkClicked:) forControlEvents: UIControlEventTouchUpInside];
[cell.contentView addSubview:check];
cellContent = [[UILabel alloc]initWithFrame:CGRectMake(40,32,500,25)];
cellContent.text = cellValue;
[cell.contentView addSubview:cellContent];
return cell;
}
-(void)checkClicked:(UIButton *)b
{
checkedImg = [UIImage imageNamed:@"buttonChecked1.png"];
[check setImage:checkedImg forState:UIControlStateNormal];
}
通過這樣做,按鈕的圖像都得到改變,但只有最後一個,而不是一個點擊。我知道背後的原因,但我不知道如何實現我想要的。
不這段代碼無法復位重新使用的電池的狀態?如果你點擊一個單元格的按鈕,然後滾動,點擊按鈕將出現在他們不應該的地方。 – occulus 2011-03-21 16:26:26
非常感謝@theChrisKent – Ashutosh 2011-03-21 16:29:27
但還有一個問題,如果用戶再次點擊,它應該再次取消選中。爲此,我將checkClicked方法更改爲: - (void)checkClicked:(UIButton *)b { \t如果(選中!){ \t \t並[b setImage:checkedImg forState:UIControlStateNormal]; \t \t檢查= YES; \t} \t else { \t \t [b setImage:unCheckedImg forState:UIControlStateNormal]; \t} \t } 但現在,如果用戶取消選中一個按鈕,然後點擊另一個按鈕它不工作,因爲布爾值更改爲YES之後。 – Ashutosh 2011-03-21 16:56:06