问题描述
我想知道是否可以将UIButton放在一段文本的精确坐标上。
I want to know if is possible to put a UIButton over a exactly coordinate of a piece of text.
例如,我的UILabel有这样的文字:
For example, my UILabel have this text:
没有账户?登录
在斜体内容中,我需要按一下按钮,触摸此按钮将触发一个操作,将打开登录视图
In the italic content, I need to put a button over then, the touch over this button will trigger an action that will open a Sign In View
非常重要使这个功能很好,在其他语言中使用它不做任何事情:)
Is very important to make this feature well, to work with same in other languages without do anything :)
谢谢
推荐答案
我会回答我的回答,因为这对于遇到同样问题的其他开发者会有所帮助。
I'll respond my answer because this can be helpful for other developers that got the same problem.
1 :你需要实现UITextViewDelegate方法:
- (BOOL)textView:shouldInteractWithURL:inRange:
1: You need to implement UITextViewDelegate method:- (BOOL)textView:shouldInteractWithURL:inRange:
实现非常简单,基本上,您将比较NSURL中收到的链接。当我有很多链接时,我喜欢使用NSURL组件通过主机进行比较,例如:
The implementation is very simple, basically, you will compare the received link in NSURL. I like to compare by host using the NSURL components when I have many links, for example:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
NSString *urlScheme = URL.scheme;
NSString *host = URL.host;
if([urlScheme isEqualToString:@"myapp"])
{
if([host isEqualToString:@"/signin"])
[self.onSignRequest( self )];
}
return YES;
}
当用户触摸链接时,将调用此方法。
This method will be called when user touch over link.
2 :创建两个 NSString
个实例,一个用于字符串Don有一个帐户?
和另一个用于字符串注册
2: Create two NSString
instances, one for the string "Don't have an account?"
and another one for string "Sign Up"
NSString *labelText = @"Don't have an account? ";
NSString *linkedText = @"Sign Up";
3 :创建 NSMutableAttributedString
两个字符串连接的实例:
3: Create a NSMutableAttributedString
instance with both strings concated:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[AttributedText attributedStringWithText:[NSString stringWithFormat:@"%@%@", labelText, linkedText]
font:[UIFOnt systemFontOfSize:14.f]
color:[UIColor blueColor]]];
4 :为可变属性字符串中的链接文本创建范围之前创建:
4: Create a range for a linked text from the mutable attributed string created before:
NSRange range = [[attributedString string] rangeOfString:linkedText];
5 :创建一个字符串
5 :为可变字符串添加新的 NSLinkAttributeName
,其中包含在步骤 4
5: Add a new NSLinkAttributeName
for the mutable string with the range created in step 4
[attributedString addAttribute:NSLinkAttributeName value:URLStringLink range:range];
6 :使用 attributionText 的属性> UILabel
_label.attributedText = attributedText;
7 :设置标签的代表:
_label.delegate = textViewDelegate;
就是这样。我希望这对任何人都需要在 UILabel
And that's it. I hope this can be helpful for anyone needs to add "touchable" links in UILabel
干杯中添加可触摸链接是有帮助的,
Cheers,
这篇关于iOS:在NSAttributedString上添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!