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

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

问题描述

在 iPhone 应用程序中,我想在 tableView 中显示信息.在每个单元格中,文字是这样的:约翰最近听音乐 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.

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

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 在第二行.

这种情况我该怎么办?

我已经搜索过:创建可点击的链接";在 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天全站免登陆