0

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.

enter image description here

4
  • You can try the TTTAttributedLabel library which supports hyperlinks: github.com/TTTAttributedLabel/TTTAttributedLabel (there are many other similar ones) Aug 25, 2015 at 3:23
  • 1
    You could also use a UIButton - not sure what makes it hard to layout Aug 25, 2015 at 3: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, 2015 at 3: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](stackoverflow.com/a/20633388/1445366 Aug 25, 2015 at 3:29

2 Answers 2

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];
1
  • That won't make the link change colors when you tap on it. Bad UX. Aug 25, 2015 at 3:30
1

I've solved by using TTTAttributedLabel! https://github.com/TTTAttributedLabel/TTTAttributedLabel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.