有時候在畫cell的時候,裡面的控件我會給它設定tag,用來在cellForRowAtIndexPath中擷取每個cell的子控件,如果子控件有個UIButton,你給它設定targeta後,在響應的方法裡沒辦法分是從哪一個cell的button觸發的,因為所有的cell的那個UIbutton的tag是一樣的。
既然不許改變tag,有沒有其他辦法知道它的父容器Cell的行數呢?知道行數了不會知道是哪一個cell的Button觸發的。
方法1:
NSString* cellStr1 = [NSString stringWithFormat:@"%d", indexPath.row];
[btn_attention setTitle:cellStr1 forState:UIControlEventTouchCancel];
擷取title,并轉為行數:
NSString* cellIndex = [sender titleForState:UIControlEventTouchCancel];
int tag =[cellIndex intValue];
方法2:
UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath * path = [self.baseTableView indexPathForCell:cell];
//擷取按鈕所在的cell的row
BnetBillMode = [self.tableArray objectAtIndex:path.row];
方法3:
[cell.button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
那麼點選button時就會調用
- (void)didTapButton:(UIButton *)sender
剩下的就是如何通過這個sender獲得它所在的cell。我們這麼實作這個方法,
- (void)didTapButton:(UIButton *)sender
{
CGRect buttonRect = sender.frame;
for (CustomCell *cell in [ self.baseTableView visibleCells])
{
if (CGRectIntersectsRect(buttonRect, cell.frame))
{
//cell就是所要獲得的
}
}
}