Is there a touch method for UILabel?

2019-02-02 07:12发布

I'd like to do an action if someone touches a predeclared UILabel, something like:

if (label is touched) {
    my actions;
}

Is there a method/way to do that?

5条回答
霸刀☆藐视天下
2楼-- · 2019-02-02 07:36

You could use a gesture recognizer:

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

- (void)didTapLabelWithGesture:(UITapGestureRecognizer *)tapGesture {
    // ...
}
查看更多
Melony?
3楼-- · 2019-02-02 07:37

By default, UILabel isn't configured to accept touch input. However, if you use a UIButton instead and set it to have a custom appearance, you can make it look like a (single-line) label and have it respond to touch events.

查看更多
混吃等死
4楼-- · 2019-02-02 07:38

You can subclass it and override the touch methods. You probably want to override touchesEnded:withEvent:.

Or just use a UIButton.

查看更多
你好瞎i
5楼-- · 2019-02-02 07:44

You need to make sure userinteractionenabled is set to YES and then you can override the touchesBegan:withEvent:

查看更多
够拽才男人
6楼-- · 2019-02-02 07:53

Just Add A category for UILabel Class and add your method to it.

查看更多
登录 后发表回答