- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents; 方法是無法傳參數的,能得到的只是響應的UIButton。下面我們來學習一下如何通過UIButton來“傳參數”。 我們以UITableView 為例,在UITableViewCell中定義一個cell,我們稱之為CustomCell,cell上加有一個UIButton的控件。我們要做的是如何在點擊UIButton時獲得cell。可以通過以下兩種方法實現。 1. 使用delegate 首先,在CustomCell類文件中定義protocol,有如下定義 @protocol CustomCellProtocol - (void)customCell:(CustomCell *)cell didTapButton:(UIButton *)button; @end 將UIButton的響應加在CustomCell文件中,比如這個響應叫做 - (IBAction)buttonTarget:(id)sender; 那么在點擊button時,就會調用這個方法。這個方法可以實現如下, - (IBAction)buttonTarget:(id)sender { if ([self.delegate respondsToSelector:@selector(customCell:didTapButton:)]) { [self.delegate performSelector:@selector(customCell:didTapButton:) withObject:self withObject:self.button]; } } 然后在UIViewController里實現代理方法,這樣,就能獲得這個UIButton所在的UITableViewCell。 2. 在ViewController中添加響應 第二種方法時在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 方法中直接給UIButton添加響應。實現如下, -(UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [atableView dequeueReusableCellWithIdentifier:@"CustomCell"]; [cell.button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside]; return cell; } 那么點擊button時就會調用 - (void)didTapButton:(UIButton *)sender 剩下的就是如何通過這個sender獲得它所在的cell。我們這么實現這個方法, - (void)didTapButton:(UIButton *)sender { CGRect buttonRect = sender.frame; for (CustomCell *cell in [tableView visibleCells]) { if (CGRectIntersectsRect(buttonRect, cell.frame)) { //cell就是所要獲得的 } } }