如何为 UILabel 的一部分设置动作?
How to set an action to a part of UILabel?
我想为 UILabel 的 "part" 设置一个动作,而不是 UIlabel 的全部,例如附图的 "term of service"。我正在使用故事板。现在,我正在考虑在 UILabel 部分覆盖 UIButton。但是,在任何布局(iPhone 5, 6 和 6 plus)通过自动布局调整带有按钮的标签部分很麻烦。如果你知道更好的方法,请告诉我。谢谢你的好意。
我建议使用 UITextView
和 NSAttributedString
。获取要查找的文本范围,然后将按钮作为子视图添加到视图中。
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];
我已经使用 TTTAttributedLabel 解决了!
https://github.com/TTTAttributedLabel/TTTAttributedLabel
我想为 UILabel 的 "part" 设置一个动作,而不是 UIlabel 的全部,例如附图的 "term of service"。我正在使用故事板。现在,我正在考虑在 UILabel 部分覆盖 UIButton。但是,在任何布局(iPhone 5, 6 和 6 plus)通过自动布局调整带有按钮的标签部分很麻烦。如果你知道更好的方法,请告诉我。谢谢你的好意。
我建议使用 UITextView
和 NSAttributedString
。获取要查找的文本范围,然后将按钮作为子视图添加到视图中。
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];
我已经使用 TTTAttributedLabel 解决了! https://github.com/TTTAttributedLabel/TTTAttributedLabel