为什么我的动作不响应选择器?

时间:2012-09-06 18:31:13

标签: ios uilabel subclass

我已经将UILabel子类化,并添加了两个如下所示的属性:

@property (nonatomic, assign) SEL action;
@property (nonatomic, assign) id target;

然后我实现了UIView的触摸开始这样的方法:

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

    if ([target respondsToSelector:@selector(action)]) {
        [target performSelector:@selector(action) onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO];
    }
}

在包含子类UILabel的类中,我设置目标和动作如下:

    label.target = self;
    labek.action = @selector(myMethod);
    label.userInteractionEnabled = YES;

包含标签的类确实具有myMethod方法,因此它应该响应它。任何想法为什么它可能不会?

谢谢!

3 个答案:

答案 0 :(得分:1)

您正在设置此行为label.action = @selector(myMethod);,然后使用操作并将其传递到第二个选择器[target respondsToSelector:@selector(action)]。那不行。

你想这样做:

if ([target respondsToSelector:self.action]) {
    [target performSelector:self.action onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO];
}

基本上,if语句失败,因为目标没有响应该选择器。因此,永远不会被召唤。

答案 1 :(得分:0)

您在调试控制台中是否收到任何错误?

怎么样

@selector(myMethod:) // with colon.

Selectors in Objective C

答案 2 :(得分:0)

确保标签包含在superview

的范围内