如何自定义UILabel可点击 [英] How to customize UILabel clickable

查看:97
本文介绍了如何自定义UILabel可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iPhone应用程序中,我想在tableView中显示信息。
在每个单元格中,文本如下:John最近听音乐abcdefg.mp3。
,如果需要,文本可以有两行。

In an iPhone app, I'd like to show information in a tableView. In each cell, the text is like: John recently listen to music abcdefg.mp3. and if needed, the text can have two lines.

在文本中,a.mp3应该是可点击的,所以当用户触摸 abcdefg时.mp3 部分,将调用另一个页面。当用户触摸 abcdefg.mp3 时,它也会产生一些效果,就像触摸按钮一样。

In the text, a.mp3 should be clickable so when the user touches the abcdefg.mp3 part, another page will be invoked. When user touches abcdefg.mp3, it will also have some effects, just like touching a button.

我计算文本的框架,并使用UIButton作为 abcdefg.mp3

I calculate the frame of the text, and I use a UIButton for abcdefg.mp3.

有时 abcdefg.mp3 可能是多行的,就像:

Sometimes abcdefg.mp3 may be in multiline, like:


abc 位于第一行的末尾

defg.mp3 在第二行。

在这种情况下我该怎么办?

What should I do in this case?

我已经搜索过:创建水龙头 - 链接在UILabel的NSAttributedString中?
但是我认为它不适合这里,因为可点击的文本全部在样本的一行中。

I've already searched about: Create tap-able "links" in the NSAttributedString of a UILabel? However I think it is not suitable here as the clickable text is all in one line in the sample.

推荐答案

最简单的方法是在实际视图中添加手势识别器(无论是UILabel还是自己的一些自定义视图)。为了使手势识别器工作,必须设置视图userInteractionEnabled。

The most simple way is to just add a gesture recognizer to the actual view (be it a UILabel or some custom view of your own). In order for the gesture recognizer to work, the view must be set userInteractionEnabled.

这是一个例子,假设您的标签视图(或其他任何东西)被称为labelView:

Here's an example, assuming that your label view (or whatever it is) is called labelView:

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTappedOnLink:)];
// if labelView is not set userInteractionEnabled, you must do so
[labelView setUserInteractionEnabled:YES];
[labelView addGestureRecognizer:gesture];

在此示例中,操作消息将发送到 self 并且消息将被定义为

In this example, an action message will be sent to self and the message would be defined as

- (void)userTappedOnLink:(UIGestureRecognizer *)gestureRecognizer;

这与连接任何其他UIControl子类(例如按钮)相同。

This works the same as wiring up any other UIControl subclass, such as a button.

其他注释:不要尝试将相同的手势识别器添加到多个视图,它将无法正常工作。不要向多个视图添加多个手势识别器副本(它不会替换它们,只是将它们堆叠起来并浪费内存)。您应该在最初创建和配置视图时添加手势识别器。

Other notes: don't try to add the same gesture recognizer to multiple views, it won't work. Don't add more than one copy of the gesture recognizer to multiple views (it doesn't replace them, it just stacks them up and wastes memory). You should add the gesture recognizer when you initially create and configure your view.

有关详细信息,请参阅 UIGestureRecognizer

For more information, see the documentation for UIGestureRecognizer.

这篇关于如何自定义UILabel可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆