【问题标题】:Is there a touch method for UILabel?UILabel 有触摸方法吗?
【发布时间】:2011-09-13 13:28:20
【问题描述】:

如果有人触摸了预先声明的UILabel,我想执行一个操作,例如:

if (label is touched) {
    my actions;
}

有没有方法/方法可以做到这一点?

【问题讨论】:

    标签: objective-c ios cocoa-touch uilabel touch-event


    【解决方案1】:

    您可以使用手势识别器:

    - (void)someSetupMethod {
        // ...
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = \
        [[UITapGestureRecognizer alloc]
         initWithTarget:self action:@selector(didTapLabelWithGesture:)];
        [label addGestureRecognizer:tapGesture];
        [tapGesture release];
    }
    
    - (void)didTapLabelWithGesture:(UITapGestureRecognizer *)tapGesture {
        // ...
    }
    

    【讨论】:

    • 如果我有多个标签,那么如何识别哪个标签被点击???
    【解决方案2】:

    默认情况下,UILabel 未配置为接受触摸输入。但是,如果您改用 UIButton 并将其设置为具有自定义外观,则可以使其看起来像(单行)标签并让它响应触摸事件。

    【讨论】:

    • 这真的很容易做到!谢谢!
    【解决方案3】:

    您可以将其子类化并覆盖触摸方法。您可能想要覆盖 touchesEnded:withEvent:

    或者只使用 UIButton。

    【讨论】:

      【解决方案4】:

      您需要确保 userinteractionenabled 设置为 YES,然后您可以覆盖 touchesBegan:withEvent:

      【讨论】:

        【解决方案5】:

        只需为 UILabel 类添加一个类别并将您的方法添加到其中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-19
          • 1970-01-01
          • 2011-12-08
          • 2018-11-29
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多