怎麼不使用didselected方法獲取選中的cell的行號,區號,indexPath

今天在開發過程中碰到這個問題,在cell中定義了button,但是點擊cell上的button並不會觸發didSelectRowAtIndexPath:這個方法

-(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開發不久,還在學習階段,有什麼錯誤希望大神指教。謝謝了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章