代码之家  ›  专栏  ›  技术社区  ›  rein

检测UITableView中按下的UIButton

  •  206
  • rein  · 技术社区  · 16 年前

    我有一个 UITableView UITableViewCells . 每个单元格包含一个 UIButton 其设置如下:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         NSString *identifier = @"identifier";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
         if (cell == nil) {
             cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
             [cell autorelelase];
    
             UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
             [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
             [button setTag:1];
             [cell.contentView addSubview:button];
    
             [button release];
         }
    
         UIButton *button = (UIButton *)[cell viewWithTag:1];
         [button setTitle:@"Edit" forState:UIControlStateNormal];
    
         return cell;
    }
    

    buttonPressedAction: 方法,如何知道按下了哪个按钮。我考虑过使用标签,但我不确定这是最好的路线。我希望能够以某种方式标记 indexPath 在控制面板上。

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        // how do I know which button sent this message?
        // processing button press for this row requires an indexPath. 
    }
    

    这样做的标准方式是什么?

    我已经通过以下步骤解决了这个问题。我仍然想知道这是标准的方法还是有更好的方法?

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         NSString *identifier = @"identifier";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
         if (cell == nil) {
             cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
             [cell autorelelase];
    
             UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
             [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
             [cell.contentView addSubview:button];
    
             [button release];
         }
    
         UIButton *button = (UIButton *)[cell.contentView.subviews objectAtIndex:0];
         [button setTag:indexPath.row];
         [button setTitle:@"Edit" forState:UIControlStateNormal];
    
         return cell;
    }
    
    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        int row = button.tag;
    }
    

    需要注意的是,我无法在创建单元时设置标记,因为单元可能会被排在队列之外。感觉很脏。一定有更好的办法。

    26 回复  |  直到 7 年前
        1
  •  401
  •   iwasrobbed    13 年前

    在苹果的 Accessory 样本使用以下方法:

    [button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    

    然后在触摸处理程序中检索触摸坐标,并根据该坐标计算索引路径:

    - (void)checkButtonTapped:(id)sender
    {
        CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
        if (indexPath != nil)
        {
         ...
        }
    }
    
        2
  •  48
  •   Cocoanut    16 年前

    我发现使用superview的superview获取对单元格的indexPath的引用的方法非常有效。感谢iphonedevbook.com(macnsmith)的提示 link text

    -(void)buttonPressed:(id)sender {
     UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
     NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
    ...
    
    }
    
        3
  •  43
  •   Iulian Onofrei Denis Oliveira    7 年前

    - (IBAction)buttonTappedAction:(id)sender
    {
        CGPoint buttonPosition = [sender convertPoint:CGPointZero
                                               toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
        ...
    }
    
        4
  •  8
  •   Imanou Petit    7 年前

    下面是5个完整的例子 为了解决你的问题。


    #1.使用 UIView convert(_:to:) UITableView indexPathForRow(at:)

    import UIKit
    
    private class CustomCell: UITableViewCell {
    
        let button = UIButton(type: .system)
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            button.setTitle("Tap", for: .normal)
            contentView.addSubview(button)
    
            button.translatesAutoresizingMaskIntoConstraints = false
            button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
            button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
            button.topAnchor.constraint(equalToSystemSpacingBelow: contentView.topAnchor, multiplier: 1).isActive = true
            button.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: contentView.leadingAnchor, multiplier: 1).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    import UIKit
    
    class TableViewController: UITableViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            cell.button.addTarget(self, action: #selector(customCellButtonTapped), for: .touchUpInside)
            return cell
        }
    
        @objc func customCellButtonTapped(_ sender: UIButton) {
            let point = sender.convert(CGPoint.zero, to: tableView)
            guard let indexPath = tableView.indexPathForRow(at: point) else { return }
            print(indexPath)
        }
    
    }
    

    #2.使用 转换(转换为:) indexPathForRow(位于:)

    这是上一个示例的另一种选择,我们将通过该示例 nil target addTarget(_:action:for:) . 这样,如果第一个响应者没有实现该操作,它将被发送到响应者链中的下一个响应者,直到找到正确的实现为止。

    import UIKit
    
    private class CustomCell: UITableViewCell {
    
        let button = UIButton(type: .system)
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            button.setTitle("Tap", for: .normal)
            button.addTarget(nil, action: #selector(TableViewController.customCellButtonTapped), for: .touchUpInside)
            contentView.addSubview(button)
    
            button.translatesAutoresizingMaskIntoConstraints = false
            button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
            button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
            button.topAnchor.constraint(equalToSystemSpacingBelow: contentView.topAnchor, multiplier: 1).isActive = true
            button.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: contentView.leadingAnchor, multiplier: 1).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    import UIKit
    
    class TableViewController: UITableViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            return cell
        }
    
        @objc func customCellButtonTapped(_ sender: UIButton) {
            let point = sender.convert(CGPoint.zero, to: tableView)
            guard let indexPath = tableView.indexPathForRow(at: point) else { return }
            print(indexPath)
        }
    
    }
    

    #3.使用 UITableView indexPath(for:)

    在本例中,我们将视图控制器设置为单元格的委托。当点击单元格的按钮时,它会触发对委托的相应方法的调用。

    import UIKit
    
    protocol CustomCellDelegate: AnyObject {
        func customCellButtonTapped(_ customCell: CustomCell)
    }
    
    class CustomCell: UITableViewCell {
    
        let button = UIButton(type: .system)
        weak var delegate: CustomCellDelegate?
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            button.setTitle("Tap", for: .normal)
            button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
            contentView.addSubview(button)
    
            button.translatesAutoresizingMaskIntoConstraints = false
            button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
            button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
            button.topAnchor.constraint(equalToSystemSpacingBelow: contentView.topAnchor, multiplier: 1).isActive = true
            button.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: contentView.leadingAnchor, multiplier: 1).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        @objc func buttonTapped(sender: UIButton) {
            delegate?.customCellButtonTapped(self)
        }
    
    }
    
    import UIKit
    
    class TableViewController: UITableViewController, CustomCellDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            cell.delegate = self
            return cell
        }
    
        // MARK: - CustomCellDelegate
    
        func customCellButtonTapped(_ customCell: CustomCell) {
            guard let indexPath = tableView.indexPath(for: customCell) else { return }
            print(indexPath)
        }
    
    }
    

    #4.使用 indexPath(用于:) 代表团结束

    import UIKit
    
    class CustomCell: UITableViewCell {
    
        let button = UIButton(type: .system)
        var buttontappedClosure: ((CustomCell) -> Void)?
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            button.setTitle("Tap", for: .normal)
            button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
            contentView.addSubview(button)
    
            button.translatesAutoresizingMaskIntoConstraints = false
            button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
            button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
            button.topAnchor.constraint(equalToSystemSpacingBelow: contentView.topAnchor, multiplier: 1).isActive = true
            button.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: contentView.leadingAnchor, multiplier: 1).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        @objc func buttonTapped(sender: UIButton) {
            buttontappedClosure?(self)
        }
    
    }
    
    import UIKit
    
    class TableViewController: UITableViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            cell.buttontappedClosure = { [weak tableView] cell in
                guard let indexPath = tableView?.indexPath(for: cell) else { return }
                print(indexPath)
            }
            return cell
        }
    
    }
    

    #5.使用 UITableViewCell accessoryType UITableViewDelegate tableView(_:accessoryButtonTappedForRowWith:)

    如果你的按钮是一个 UITableViewCell 的标准附件控制,任何轻触都会触发呼叫 委托协议 ,允许您获取相关的索引路径。

    import UIKit
    
    private class CustomCell: UITableViewCell {
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            accessoryType = .detailButton
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    import UIKit
    
    class TableViewController: UITableViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 3
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            return cell
        }
    
        override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
            print(indexPath)
        }
    
    }
    
        5
  •  6
  •   Iulian Onofrei Denis Oliveira    7 年前

    在别处找到了一个很好的解决方案,没有在按钮上乱动标签:

    - (void)buttonPressedAction:(id)sender {
    
        NSSet *touches = [event allTouches];
        UITouch *touch = [touches anyObject];
        CGPoint currentTouchPosition = [touch locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    
        // do stuff with the indexPath...
    }
    
        6
  •  5
  •   Paras Joshi    13 年前

    像这样发送信息怎么样 NSIndexPath UIButton 使用运行时注入。

    1) 导入时需要运行时

    2) 加上静态常数

    3) 加

    (void)setMetaData:(id)targetwithObject:(id)newObj

    4) 在按钮上,按获取元数据,使用:

    享受

        #import <objc/runtime.h>
        static char const * const kMetaDic = "kMetaDic";
    
    
        #pragma mark - Getters / Setters
    
    - (id)metaData:(id)target {
        return objc_getAssociatedObject(target, kMetaDic);
    }
    
    - (void)setMetaData:(id)target withObject:(id)newObj {
        objc_setAssociatedObject(target, kMetaDic, newObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    
    
        #On the cell constructor
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
        ....
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        ....
        [btnSocial addTarget:self
                                       action:@selector(openComments:)
                             forControlEvents:UIControlEventTouchUpInside];
    
        #add the indexpath here or another object
        [self setMetaData:btnSocial withObject:indexPath];
    
        ....
        }
    
    
    
        #The action after button been press:
    
        - (IBAction)openComments:(UIButton*)sender{
    
            NSIndexPath *indexPath = [self metaData:sender];
            NSLog(@"indexPath: %d", indexPath.row);
    
            //Reuse your indexpath Now
        }
    
        7
  •  5
  •   Adrian rohit chauhan    9 年前

    ToDo(@Vladimir)的回答很快:

    var buttonPosition = sender.convertPoint(CGPointZero, toView: self.tableView)
    var indexPath = self.tableView.indexPathForRowAtPoint(buttonPosition)!
    

    虽然正在检查 indexPath != nil

        8
  •  5
  •   Iulian Onofrei Denis Oliveira    7 年前
    func buttonAction(sender:UIButton!)
        {
            var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tablevw)
            let indexPath = self.tablevw.indexPathForRowAtPoint(position)
            let cell: TableViewCell = tablevw.cellForRowAtIndexPath(indexPath!) as TableViewCell
            println(indexPath?.row)
            println("Button tapped")
        }
    
        9
  •  3
  •   ACBurk    16 年前

    我会像您所说的那样使用tag属性,将标记设置为:

    [button setTag:indexPath.row];
    

    然后将标签放在按钮内按下,如下所示:

    ((UIButton *)sender).tag
    

    UIButton *button = (UIButton *)sender; 
    button.tag;
    
        10
  •  3
  •   Paras Joshi    13 年前

    虽然我喜欢标签的方式。。。如果您不想出于任何原因使用标记, 您可以创建一个成员 NSArray 预制按钮的数量:

    NSArray* buttons ;
    

    然后在呈现tableView之前创建这些按钮,并将它们推入数组中。

    然后在 tableView:cellForRowAtIndexPath:

    UIButton* button = [buttons objectAtIndex:[indexPath row] ] ;
    [cell.contentView addSubview:button];
    

    然后在 buttonPressedAction: 功能,你可以做

    - (void)buttonPressedAction:(id)sender {
       UIButton* button = (UIButton*)sender ;
       int row = [buttons indexOfObject:button] ;
       // Do magic
    }
    
        11
  •  2
  •   brian.clear    13 年前

    在CLKIndexPricesHEADERTableViewCell.xib中

    在IB中,将UIButton添加到XIB-不要添加操作!

    @interface CLKIndexPricesHEADERTableViewCell : UITableViewCell
    ...
    @property (retain, nonatomic) IBOutlet UIButton *buttonIndexSectionClose;
    @property (nonatomic, retain) NSIndexPath * indexPathForCell;
    @end
    

    在viewForHeaderInSection中(如果您的表只有1个部分,则也应适用于cellForRow…等)

    - viewForHeaderInSection is called for each section 1...2...3
    - get the cell CLKIndexPricesHEADERTableViewCell 
    - getTableRowHEADER just does the normal dequeueReusableCellWithIdentifier
    - STORE the indexPath IN the UITableView cell
    - indexPath.section = (NSInteger)section
    - indexPath.row = 0 always (we are only interested in sections)
    
    - (UIView *) tableView:(UITableView *)tableView1 viewForHeaderInSection:(NSInteger)section {
    
    
        //Standard method for getting a UITableViewCell
        CLKIndexPricesHEADERTableViewCell * cellHEADER = [self getTableRowHEADER];
    

    …使用节获取单元格的数据

       indexName        = ffaIndex.routeCode;
       indexPrice       = ffaIndex.indexValue;
    
       //
    
       [cellHEADER.buttonIndexSectionClose addTarget:self
                                              action:@selector(buttonDELETEINDEXPressedAction:forEvent:)
                                    forControlEvents:UIControlEventTouchUpInside];
    
    
       cellHEADER.indexPathForCell = [NSIndexPath indexPathForRow:0 inSection:section];
    
    
        return cellHEADER;
    }
    

    用户按下节标题上的“删除”按钮,这将调用

    - (void)buttonDELETEINDEXPressedAction:(id)sender forEvent:(UIEvent *)event
    {
        NSLog(@"%s", __PRETTY_FUNCTION__);
    
    
        UIView *  parent1 = [sender superview];   // UiTableViewCellContentView
        //UIView *myContentView = (UIView *)parent1;
    
        UIView *  parent2 = [parent1 superview];  // custom cell containing the content view
        //UIView *  parent3 = [parent2 superview];  // UITableView containing the cell
        //UIView *  parent4 = [parent3 superview];  // UIView containing the table
    
    
        if([parent2 isMemberOfClass:[CLKIndexPricesHEADERTableViewCell class]]){
            CLKIndexPricesHEADERTableViewCell *myTableCell = (CLKIndexPricesHEADERTableViewCell *)parent2;
    
            //UITableView *myTable = (UITableView *)parent3;
            //UIView *mainView = (UIView *)parent4;
    
            NSLog(@"%s indexPath.section,row[%d,%d]", __PRETTY_FUNCTION__, myTableCell.indexPathForCell.section,myTableCell.indexPathForCell.row);
    
            NSString *key = [self.sortedKeysArray objectAtIndex:myTableCell.indexPathForCell.section];
            if(key){
                NSLog(@"%s DELETE object at key:%@", __PRETTY_FUNCTION__,key);
                self.keyForSectionIndexToDelete = key;
                self.sectionIndexToDelete = myTableCell.indexPathForCell.section;
    
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Remove Index"
                                                                    message:@"Are you sure"
                                                                   delegate:self
                                                          cancelButtonTitle:@"No"
                                                          otherButtonTitles:@"Yes", nil];
                alertView.tag = kALERTVIEW_REMOVE_ONE_INDEX;
                [alertView show];
                [alertView release];
                //------
            }else{
                NSLog(@"ERROR: [%s] key is nil for section:%d", __PRETTY_FUNCTION__,myTableCell.indexPathForCell.section);
            }
    
        }else{
            NSLog(@"ERROR: [%s] CLKIndexPricesHEADERTableViewCell not found", __PRETTY_FUNCTION__);
        }
    }
    

    在这个例子中,我添加了一个删除按钮,所以应该显示UIAlertView来确认它

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
       if(alertView.tag == kALERTVIEW_REMOVE_ONE_INDEX){
            if(buttonIndex==0){
                //NO
                NSLog(@"[%s] BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
                //do nothing
            }
            else if(buttonIndex==1){
                //YES
                NSLog(@"[%s] BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
                if(self.keyForSectionIndexToDelete != nil){
    
                    //Remove the section by key
                    [self.indexPricesDictionary removeObjectForKey:self.keyForSectionIndexToDelete];
    
                    //sort the keys so sections appear alphabetically/numbericsearch (minus the one we just removed)
                    [self updateTheSortedKeysArray];                
    
                    //Delete the section from the table using animation
                    [self.tableView beginUpdates];
    
                    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:self.sectionIndexToDelete]
                                  withRowAnimation:UITableViewRowAnimationAutomatic];
                    [self.tableView endUpdates];
    
                    //required to trigger refresh of myTableCell.indexPathForCell else old values in UITableViewCells
                    [self.tableView reloadData];
                }else{
                    NSLog(@"ERROR: [%s] OBJECT is nil", __PRETTY_FUNCTION__);
                }
            }
            else {
                NSLog(@"ERROR: [%s] UNHANDLED BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
            }
        }else {
            NSLog(@"ERROR: [%s] unhandled ALERTVIEW TAG:%d", __PRETTY_FUNCTION__,alertView.tag);
        }
    }
    
        12
  •  2
  •   mmmanishs    12 年前
    A better way would be to subclass your button and add a indexPath property to it.
    
    //Implement a subclass for UIButton.
    
    @interface NewButton:UIButton
    @property(nonatomic, strong) NSIndexPath *indexPath;
    
    
    Make your button of type NewButton in the XIB or in the code whereever you are initializing them.
    
    Then in the cellForRowAtIndexPath put the following line of code.
    
    button.indexPath = indexPath;
    
    return cell; //As usual
    
    
    
    Now in your IBAction
    
    -(IBAction)buttonClicked:(id)sender{
       NewButton *button = (NewButton *)sender;
    
    //Now access the indexPath by buttons property..
    
       NSIndexPath *indexPath = button.indexPath; //:)
    }
    
        13
  •  1
  •   user366584    15 年前

    这对我也有用,谢谢@Cocoanut

    -(void)buttonPressed:(id)sender {
     UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
     NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
    ...
    
    }
    
        14
  •  0
  •   Nir Levy    16 年前

    您可以使用标记模式:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         NSString *identifier = @"identifier";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
         if (cell == nil) {
             cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
             [cell autorelelase];
    
             UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
             [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
             [button setTag:[indexPath row]]; //use the row as the current tag
             [cell.contentView addSubview:button];
    
             [button release];
         }
    
         UIButton *button = (UIButton *)[cell viewWithTag:[indexPath row]]; //use [indexPath row]
         [button setTitle:@"Edit" forState:UIControlStateNormal];
    
         return cell;
    }
    
    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        //button.tag has the row number (you can convert it to indexPath)
    }
    
        15
  •  0
  •   Michael Morrison    16 年前

    我错过什么了吗?你不能用sender来识别按钮吗。发件人将向您提供如下信息:

    <UIButton: 0x4b95c10; frame = (246 26; 30 30); opaque = NO; tag = 104; layer = <CALayer: 0x4b95be0>>
    

    然后,如果您想更改按钮的属性,请说出您刚刚告诉发件人的背景图像:

    [sender setBackgroundImage:[UIImage imageNamed:@"new-image.png"] forState:UIControlStateNormal];
    

        16
  •  0
  •   ohhorob    15 年前
    // how do I know which button sent this message?
    // processing button press for this row requires an indexPath.
    

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        CGPoint rowButtonCenterInTableView = [[rowButton superview] convertPoint:rowButton.center toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rowButtonCenterInTableView];
        MyTableViewItem *rowItem = [self.itemsArray objectAtIndex:indexPath.row];
        // Now you're good to go.. do what the intention of the button is, but with
        // the context of the "row item" that the button belongs to
        [self performFooWithItem:rowItem];
    }
    

    对我来说很好:P

    如果要调整目标动作设置,可以在方法中包含事件参数,然后使用该事件的触碰来解析触碰的坐标。坐标仍然需要在触摸视图边界中解析,但对于某些人来说,这似乎更容易。

        17
  •  0
  •   rajesh    15 年前

    创建一个nsmutable数组,并使用[array addObject:yourButton]将all按钮放入该数组中;

    按按钮的方法

     (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
    
    for(int i=0;i<[yourArray count];i++){
    
    if([buton isEqual:[yourArray objectAtIndex:i]]){
    
    //here write wat u need to do
    
    }
    }
    
        18
  •  0
  •   software evolved    14 年前

    当按钮位于表的页脚时,Cocoanuts的答案有一点变化(这帮助我解决了这个问题)(这会阻止您找到“单击的单元格”):

    -(IBAction) buttonAction:(id)sender;
    {
        id parent1 = [sender superview];   // UiTableViewCellContentView
        id parent2 = [parent1 superview];  // custom cell containing the content view
        id parent3 = [parent2 superview];  // UITableView containing the cell
        id parent4 = [parent3 superview];  // UIView containing the table
    
        UIView *myContentView = (UIView *)parent1;
        UITableViewCell *myTableCell = (UITableViewCell *)parent2;
        UITableView *myTable = (UITableView *)parent3;
        UIView *mainView = (UIView *)parent4;
    
        CGRect footerViewRect = myTableCell.frame;
        CGRect rect3 = [myTable convertRect:footerViewRect toView:mainView];    
    
        [cc doSomethingOnScreenAtY:rect3.origin.y];
    }
    
        19
  •  0
  •   Paras Joshi    13 年前

    您需要将 UITableviewCell 然后从那里按下按钮。

        20
  •  0
  •   Paras Joshi    13 年前

    这很简单;制作一个自定义单元格并取一个按钮的出口

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
             NSString *identifier = @"identifier";
            customCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
        cell.yourButton.tag = indexPath.Row;
    
    - (void)buttonPressedAction:(id)sender
    

    将上述方法中的id更改为 (UIButton *)

    您可以通过执行sender.tag来获取正在点击哪个按钮的值。

        21
  •  0
  •   Jerome Chan Yeow Heong    12 年前

        22
  •  0
  •   Lukesivi    10 年前

    SWIFT 2更新

    下面是如何找出被点击的按钮,并从该按钮的位置向另一个ViewController发送数据 indexPath.row

    @IBAction func yourButton(sender: AnyObject) {
    
    
         var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
            let indexPath = self.tableView.indexPathForRowAtPoint(position)
            let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
            UITableViewCell
            print(indexPath?.row)
            print("Tap tap tap tap")
    
        }
    

    下面是在点击该按钮并传递数据时将数据传递给另一个VC的代码 细胞的

    @IBAction func moreInfo(sender: AnyObject) {
    
        let yourOtherVC = self.storyboard!.instantiateViewControllerWithIdentifier("yourOtherVC") as! YourOtherVCVIewController
    
    
    
        var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(position)
        let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
        UITableViewCell
        print(indexPath?.row)
        print("Button tapped")
    
    
        yourOtherVC.yourVarName = [self.otherVCVariable[indexPath!.row]]
    
        self.presentViewController(yourNewVC, animated: true, completion: nil)
    
    }
    
        23
  •  0
  •   Sangram Shivankar Wostein    10 年前

     @IBAction func call(sender: UIButton)
        {
            var contentView = sender.superview;
            var cell = contentView?.superview as EmployeeListCustomCell
            if (!(cell.isKindOfClass(EmployeeListCustomCell)))
            {
                cell = (contentView?.superview)?.superview as EmployeeListCustomCell
            }
    
            let phone = cell.lblDescriptionText.text!
            //let phone = detailObject!.mobile!
            let url:NSURL = NSURL(string:"tel://"+phone)!;
            UIApplication.sharedApplication().openURL(url);
        }
    
        24
  •  0
  •   Rutger Huijsmans    9 年前

    Chris Schwerdt的解决方案但在Swift中对我起了作用:

    @IBAction func rateButtonTapped(sender: UIButton) {
        let buttonPosition : CGPoint = sender.convertPoint(CGPointZero, toView: self.ratingTableView)
        let indexPath : NSIndexPath = self.ratingTableView.indexPathForRowAtPoint(buttonPosition)!
    
        print(sender.tag)
        print(indexPath.row)
    }
    
        25
  •  0
  •   erkanyildiz    9 年前

    UITableViewCell 里面有压过的 UIButton

    以下是一些建议:

    • 更新 UIButton tag 在里面 cellForRowAtIndexPath: 方法使用索引路径的 row 连续,它不适用于具有多个分区的表视图。

    • 添加 NSIndexPath UIButton 标签 在里面 cellForRowAtIndexPath:

    • 对父母保持微弱的参照 UITableView indexPathForCell: 方法来获取索引路径。看起来好多了,不需要更新任何东西 cellForRowAtIndexPath:

    • 使用细胞的 superView 属性以获取对父对象的引用 . 无需向自定义单元格添加任何属性,也无需在创建/以后设置/更新任何内容。但是手机 超级视图 取决于iOS实施细节。因此不能直接使用。

    UIView* view = self;
    while (view && ![view isKindOfClass:UITableView.class])
        view = view.superview;
    UITableView* parentTableView = (UITableView*)view;
    

    因此,可以将这些建议组合成一种简单而安全的自定义单元格方法来获取索引路径:

    - (NSIndexPath *)indexPath
    {
        UIView* view = self;
    
        while (view && ![view isKindOfClass:UITableView.class])
            view = view.superview;
    
        return [(UITableView*)view indexPathForCell:self];
    }
    

    从现在起,这种方法可以用来检测 UIButton

    在内部知道 UITableView )。因此,此按钮单击事件可以在与 didSelectRowAtIndexPath:

    有两种方法可用于此目的:

    a) 代表团: 自定义单元格可以有一个 delegate 属性,可以定义协议。当按下按钮时,它只在其上执行它的委托方法 代表 代表 创建每个自定义单元格时,需要为其设置属性。或者,自定义单元格可以选择在其父表视图的

    b) 通知中心: userInfo

        26
  •  0
  •   Ben Ong    8 年前

    我使用的解决方案是 UIButton

    class ButtonWithIndexPath : UIButton {
        var indexPath:IndexPath?
    }
    

    然后记得在中更新它的indexPath cellForRow(at:)

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let returnCell = tableView.dequeueReusableCell(withIdentifier: "cellWithButton", for: indexPath) as! cellWithButton
        ...
        returnCell.button.indexPath = IndexPath
        returnCell.button.addTarget(self, action:#selector(cellButtonPressed(_:)), for: .touchUpInside)
    
        return returnCell
    }
    

    因此,当响应按钮的事件时,您可以像

    func cellButtonPressed(_ sender:UIButton) {
        if sender is ButtonWithIndexPath {
            let button = sender as! ButtonWithIndexPath
            print(button.indexPath)
        }
    }