Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

iphone - How to customize UILabel clickable

What I want:

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.

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.

What I do:

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

My Problem:

Sometimes abcdefg.mp3 may be in multiline, like:

abc is at the end of the first line

defg.mp3 is in second line.

What should I do in this case?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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];

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

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

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.

For more information, see the documentation for UIGestureRecognizer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...