有時候在畫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就是所要得到的
}
}
}
ide