-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
所以可以採用曲線救國的方法 將所有的button全部響應同一個方法,然後在方法中判斷是哪一行。
代碼片段如下,先創建一個cell
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
//創建cell
static NSString *identify = @"identify";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
}
//給cell賦值
UIButton *btn = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 64, 44)];
[cell.contentView addSubview:btn];
[btn addTarget:self action:@selector(BtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
//返回cell
return cell;
}
然後寫出相應的相應方法,一定要確定superView幾次後能得到自己的cell。因爲我的是在cell中只定義了一個button
所以方向是self(btn) -> contentView -> cell。即需要兩次superView。
- (void) rightBtnDidClick:(UIButton *)sender{
//一定要確定上superView幾次後得到的是cell
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
NSLog(@"%ld",indexpath.row);
}
剛接觸ios開發不久,還在學習階段,有什麼錯誤希望大神指教。謝謝了。