I'd like to set an action to a "part" of UILabel not the all of UIlabel, like the "term of service" of attached picture. I am using storyboard. Now, I'm thinking to cover the UIButton over the part of UILabel. However, it is troublesome to adjust the part of label with the button at any layout(iPhone 5, 6 and 6 plus) by autolayout. If you know better way, please tell me. Thank you for your kindness.
Asked
Active
Viewed 1,254 times
0
-
You can try the TTTAttributedLabel library which supports hyperlinks: https://github.com/TTTAttributedLabel/TTTAttributedLabel (there are many other similar ones) – Aaron Brager Aug 25 '15 at 03:23
-
1You could also use a `UIButton` - not sure what makes it hard to layout – Aaron Brager Aug 25 '15 at 03:23
-
Dear Aaron Thank you! In terms of UIButton, should I prepare UIlabel and UIButton, the label "By continuing you indicate that you have read and agree to the" and the button "Terms of Service"? – Toshi Aug 25 '15 at 03:26
-
I guess it's a little bit of a pain, but you can get the rect for a specific line of text [by using `NSTextContainer`](http://stackoverflow.com/a/20633388/1445366 – Aaron Brager Aug 25 '15 at 03:29
2 Answers
1
I'd recommend using a UITextView
with an NSAttributedString
. Get the range of the text you are looking for, and then add the button as a subview to the view.
NSRange termsOfServiceRange = [self.termsOfUseTextView.text rangeOfString:@"Terms of Service"];
self.termsOfUseTextView.selectedRange = termsOfServiceRange;
UITextRange *termsOfServiceTextRange = [self.termsOfUseTextView selectedTextRange];
CGRect termsOfServiceFrame = [self.termsOfUseTextView firstRectForRange:termsOfServiceTextRange];
CGRect convertedFrame = [self.view convertRect:termsOfServiceFrame fromView:self.termsOfUseTextView];
UIButton *termsOfServiceButton = [[UIButton alloc]initWithFrame:convertedFrame];
[termsOfServiceButton setBackgroundColor:[UIColor clearColor]];
[termsOfServiceButton addTarget:self action:@selector(termsOfServiceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:termsOfServiceButton];
[self.view bringSubviewToFront:termsOfServiceButton];

Tommy Devoy
- 13,441
- 3
- 48
- 75
-
That won't make the link change colors when you tap on it. Bad UX. – Aaron Brager Aug 25 '15 at 03:30
1
I've solved by using TTTAttributedLabel! https://github.com/TTTAttributedLabel/TTTAttributedLabel

Toshi
- 1,293
- 3
- 19
- 37