【问题标题】:How can I use a button in a cell (placed with StoryBoard)如何在单元格中使用按钮(与 StoryBoard 一起放置)
【发布时间】:2014-02-27 22:46:23
【问题描述】:

我正在寻找一种在单元格中使用按钮的方法。我在表格视图的原型单元格中创建了它,但是当我点击它时无法检测到它所在的单元格。

你能帮帮我吗?

【问题讨论】:

    标签: ios button cell detect


    【解决方案1】:

    假设这个 IBAction 是您点击按钮时的事件处理程序:

    -   (IBAction) buttonTapped: (UIButton *) sender
        {
           //get parent cell 
           UITableViewCell *cell = [sender findSuperViewWithClass:[UITableViewCell class]];
           //do whatever you want...
        }
    

    你需要这个类别的地方:

    @implementation UIView (SuperView)
    
    - (UIView *)findSuperViewWithClass:(Class)superViewClass
    {
        UIView *superView = self.superview;
        UIView *foundSuperView = nil;
    
        while (nil != superView && nil == foundSuperView) {
            if ([superView isKindOfClass:superViewClass]) {
                foundSuperView = superView;
                break;
            } else {
                superView = superView.superview;
            }
        }
        return foundSuperView;
    }
    
    @end
    

    【讨论】:

    • 这是不正确的。单元格不是按钮的超级视图。在 iOS 7 中,按钮和单元格之间还有另外两个视图(contentView 和滚动视图),而在 iOS 6 中只有一个。如果您打算使用这种方法,您需要查找其类是 UITableViewCell 或其子类的对象的超级视图链。
    • 太糟糕了,那样会很容易:p
    • @rdelmar:是的,我已经更新了我的答案,请检查
    • @user3362642:你能用更新的答案做到吗?
    • 我正在尝试,但我不知道最后一部分的去向 xD(我是 obj-c 的初学者)
    【解决方案2】:

    “我在自定义单元格中处理按钮的方式:

    • 我定义了一个连接到自定义单元格内的 UIButton 事件的 IBAction
    • 我为单元格定义了一个委托和一个委托方法来处理按钮操作
    • IBAction 调用该委托方法
    • 在 cellAtRow 中定义单元格时...我将 tableViewController 设置为委托。 cell.delegate=self;
    • 我在 tableViewController 的委托方法中执行我想做的任何操作

    "

    来自JP HribovsekHandle button click inside UITableViewCell的回答

    【讨论】:

    • 似乎不起作用,“在 UITableViewCell* 中找不到属性委托”
    【解决方案3】:
    - (void)buttonOnCellTapped:(id)sender
    {        
        CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.table];
        NSIndexPath *indexPath = [self.table indexPathForRowAtPoint:buttonPosition];
        if (indexPath)
        {
            NSLog(@"BUTTON TAPPED ON SECTION: %d, ROW: %d", indexPath.section, indexPath.row);
            UITableViewCell *cell = [self.table cellForRowAtIndexPath:indexPath];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2012-01-08
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多