Jan*_*sio 2 uibutton nsattributedstring ios
我想知道是否可以将UIButton放在一段文本的精确坐标上.
例如,我的UILabel有这样的文字:
"没有账号?登录 "
在斜体内容中,我需要在此处按下按钮,触摸此按钮将触发将打开登录视图的操作
非常重要的是要使这个功能很好,在其他语言中使用相同而不做任何事情:)
谢谢
我会回答我的回答,因为这对于遇到同样问题的其他开发人员有帮助.
1:您需要实现UITextViewDelegate方法:
- (BOOL)textView:shouldInteractWithURL:inRange:
实现非常简单,基本上,您将比较NSURL中收到的链接.当我有许多链接时,我喜欢使用NSURL组件通过主机进行比较,例如:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
当用户触摸链接时,将调用此方法.
2:创建两个NSString实例,一个用于字符串"Don't have an account?",另一个用于字符串"Sign Up"
NSString *labelText = @"Don't have an account? ";
NSString *linkedText = @"Sign Up";
Run Code Online (Sandbox Code Playgroud)
3:创建一个NSMutableAttributedString两个字符串的实例:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[AttributedText attributedStringWithText:[NSString stringWithFormat:@"%@%@", labelText, linkedText]
font:[UIFOnt systemFontOfSize:14.f]
color:[UIColor blueColor]]];
Run Code Online (Sandbox Code Playgroud)
4:为之前创建的可变属性字符串创建链接文本的范围:
NSRange range = [[attributedString string] rangeOfString:linkedText];
Run Code Online (Sandbox Code Playgroud)
5:创建一个字符串
5:NSLinkAttributeName为可变字符串添加一个新的,其中包含在步骤4中创建的范围
[attributedString addAttribute:NSLinkAttributeName value:URLStringLink range:range];
Run Code Online (Sandbox Code Playgroud)
6:使用attributedText属性of 将可变字符串添加到UILabelUILabel
_label.attributedText = attributedText;
Run Code Online (Sandbox Code Playgroud)
7:设置标签的代表:
_label.delegate = textViewDelegate;
Run Code Online (Sandbox Code Playgroud)
就是这样.我希望这对任何需要添加"可触摸"链接的人都有帮助UILabel
干杯,
| 归档时间: |
|
| 查看次数: |
3966 次 |
| 最近记录: |