美文网首页
iOS 为自定义tableView添加button点击事件后获取

iOS 为自定义tableView添加button点击事件后获取

作者: _10_01_ | 来源:发表于2017-11-23 11:09 被阅读254次

转载:http://www.cnblogs.com/fookehi/p/3797788.html

在自定义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所在的序号
}

相关文章

网友评论

      本文标题:iOS 为自定义tableView添加button点击事件后获取

      本文链接:https://www.haomeiwen.com/subject/iptzvxtx.html