iOS 為自訂tableView添加button點擊事件後擷取其序號

來源:互聯網
上載者:User

標籤:style   color   get   os   cti   for   

在自訂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所在的序號
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.