2011-10-12 111 views
0

好吧,我有一個表格視圖,可以添加和刪除單元格。對於添加的每個單元格,它會在單元格中獲得兩個按鈕,一個加減按鈕,從單元格的textLabel中添加1和子1。但是當我按下1個單元格按鈕時,它會從另一個單元格textLabel下載。這裏是我的cellForRow方法:表格視圖單元格的按鈕與其他單元格混淆?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  
(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell"; 

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) 
{ 
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
reuseIdentifier:CellIdentifier]; 
} 
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];  
cell.textLabel.text = [cells objectAtIndex:indexPath.row]; 

newBtn = [[UIButton alloc]init]; 
newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[newBtn setFrame:CGRectMake(195,20,55,35)]; 
[newBtn addTarget:self action:@selector(subtractLabelText:) 
forControlEvents:UIControlEventTouchUpInside]; 
[newBtn setTitle:@"-" forState:UIControlStateNormal]; 
[cell addSubview:newBtn]; 

return cell; 
} 

接下來的這個方法是方法是一個我迷上了減法按鈕:

- (IBAction)subtractLabelText:(id)sender{ 

if ([[cell.textLabel text] intValue] == 0){ 
[newBtn setEnabled:NO]; 
} 
else{ 
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text 
intValue] -1]; 
    } 
} 

請幫助!非常感謝! :D

回答

2

您應該傳遞該單元格作爲參數subtractLabelText:,否則此函數不知道它訪問哪個單元格。


我想到的,我是做的是在一條線上添加定義單元格的最簡單的事情:當涉及到編碼

- (IBAction)subtractLabelText:(id)sender{ 

UITableViewCell *cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE 

if ([[cell.textLabel text] intValue] == 0){ 
[newBtn setEnabled:NO]; 
} 
else{ 
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text 
intValue] -1]; 
    } 
} 
+0

即時通訊相當noobish呵呵!好吧,如果我的單元格名稱是單元格,我該如何編寫參數?像 - (void)subtractLabelText:(UITableViewCell *)單元格?還是有另一種方式?非常感謝!! :D – iProRage

+0

@iProRage查看我的更新。請停止轉貼此評論。 – PengOne

+0

作品完美!非常感謝!! :D:D – iProRage

相關問題