【问题标题】:Custom delegate not calling UITableViewController method自定义委托未调用 UITableViewController 方法
【发布时间】:2016-11-17 15:39:02
【问题描述】:

我有一个自定义 UIButton 类,如下所示:

.h

#import <UIKit/UIKit.h>

@class FriendButton;
@protocol LongPressedButtonDelegate
- (void)buttonIsLongPressed:(FriendButton *)button;
@end

@interface FriendButton : UIButton
@property (nonatomic, weak) id<LongPressedButtonDelegate > delegate;
@end

.m

@implementation FriendButton




//this is called from the interface builder
-(id) initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:(NSCoder *)aDecoder];
    NSLog(@"init called");
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    [self addGestureRecognizer:longPress];

    return self;

}

-(void)longPress:(id)sender {
    NSLog(@"long press");
    [self.delegate buttonIsLongPressed:self];
}

@end

我的按钮在界面构建器中设置,它们包含在 UITableView 单元格中。在我的 UITableViewController 我有:

-(void)buttonIsLongPressed:(FriendButton *)button {

    NSLog(@"Delegate method!");

}

并且它的控制器符合协议。长按手势有效,但未调用委托方法。我不确定为什么它不起作用。是因为我必须将每个按钮委托给 UITableViewController 吗?如果是这样,我会怎么做?按钮在界面生成器中设置。

【问题讨论】:

  • 您尚未将 LongPressedButtonDelegate 链接到 UITableViewController。所以它的委托是零
  • 您必须创建某种出口并执行 longPressButtonOutlet.delete = self.

标签: ios objective-c xcode uitableview


【解决方案1】:

以这种方式定义您的 UIButton 属性

@interface FriendButton : UIButton
@property (nonatomic, weak) IBOutlet id<LongPressedButtonDelegate > delegate;
@end

然后转到 Interface Builder 并右键单击 UIButton,您将看到委托将此委托链接到 UITableViewController。它应该工作

【讨论】:

    【解决方案2】:

    在 UITableViewController 的 cellForRowAtIndexPath 实现中,您需要执行以下操作:

    cell.button.delegate = self;
    

    编辑:如果您想以编程方式执行此操作。如果您想在情节提要中这样做,请参阅有关 IBOutlets 的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多