iOS 為自定義tableView添加button點擊事件后獲取其序號


在自定義tableView中,為cell添加button點擊事件后,如何獲取其對應的序號?

1、創建tableView:

先創建一個成員變量:

@interface MyCameraViewController ()<UITableViewDelegate,UITableViewDataSource>

{

  UITableView *_tableView;

}@end

在viewDidLoad中初始化

_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, 320, [UIScreen mainScreen].bounds.size.height-65) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];

2、實現其必須實現的代理方法

#pragma mark - Table view data source

//組數
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
//cell的個數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 10;
}

3、創建cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // Configure the cell...
        if (nil == cell) {
         cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    cell.textLable.text = @"hello,你好";

    UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
            CGRect frame = CGRectMake( 0.0 , 0.0 , 30 , 24 );
            button.frame = frame;
  //          [button setImage:image forState:UIControlStateNormal ];    //可以給button設置圖片
//            button.backgroundColor = [UIColor clearColor ];
            [button addTarget:self action:@selector(accessoryButtonTappedAction:) forControlEvents:UIControlEventTouchUpInside];

    //將該button賦給cell屬性accessoryView
            cell. accessoryView = button;
  }

  return cell;

}

 

//實現button的點擊事件
- (void)accessoryButtonTappedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    UITableViewCell  *cell;
    if (iOS7) {
        cell = (UITableViewCell *)button.superview.superview;
    }else
    {
        cell = (UITableViewCell *)button.superview;
    }
    int row = [_tableView indexPathForCell:cell].row;  //row為該button所在的序號
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM