【问题标题】:iPhone: how to detect when user clicks a button in a customized UITableViewCelliPhone:如何检测用户何时单击自定义 UITableViewCell 中的按钮
【发布时间】:2011-07-06 01:29:07
【问题描述】:

我创建了一个在UITableViewCell (cellForRowAtIndexPath) 中调用的自定义调用。一切都很好,但后来我在单元格中添加了一个按钮 (UIButton)。按钮的“引用插座”是自定义单元格。

当用户单击按钮时,我无法确定如何阅读。是否需要在包含表格或自定义单元格标题的头文件中声明委托方法?

我尝试了- (void)buttonPressedAction:(id)sender {} 方法,但它似乎没有检测到何时按下按钮

我也试过了:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

NSSet *aTouch = [event allTouches];
UITouch *touch = [aTouch anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.dashboardTable];
NSIndexPath *indexPath = [self.dashboardTable indexPathForRowAtPoint: currentTouchPosition];

NSLog(@"indexPath %@",indexPath);

}

但同样,单击按钮时没有任何记录。我尝试将 UIGestureRecognizerDelegate 添加到 .h 但没有运气。

感谢任何帮助。

【问题讨论】:

    标签: iphone button sdk uitableview delegates


    【解决方案1】:

    您需要设置按钮的操作。如果你这样做是一个XIB,你所要做的就是控制点击按钮,然后拖动到控制器。这应该会为您提供按钮可用的操作列表。

    要在代码中执行此操作,您将使用 - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 方法。

    [myButton addTarget:myTargetController action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
    

    【讨论】:

    • 嗨,索斯伯恩。您上面提到的代码是放在 CustomCell 的 .h 和 .m 中,还是放在调用(使用)CustomCell 的类中?令人困惑的是“myButton”在主类(表格部分)中工作,但是当我在上面添加新方法时编译器会抱怨。很奇怪。
    • 理想情况下,代码应该在您创建按钮的同时执行。但是,如果不知道一切是如何设置的,就很难准确地告诉你什么是正确的。你必须让它适应你的情况。编译器会给你什么警告?
    • 所以我编辑了 CustomCell 并添加了这个方法: -(IBAction) clickButton: (id)sender { NSLog(@"clicked"); }。我现在每次按下按钮时都会收到一条日志消息(来自 CustomCell 类),但我怎么知道找到与按下的特定按钮相对应的行号? (来自调用 CustomCell 的类?)我尝试了 addTarget 但没有任何反应 帮助赞赏。
    • int row = [myTableView indexPathForCell:self].row
    猜你喜欢
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2015-10-07
    • 2019-12-23
    相关资源
    最近更新 更多