如何使UILabel文本中的两个或多个字符串指向不同的链接
问题描述:
我有一个显示字符串的UILabel。我需要改变UILabel中特定文本的颜色,当点击这些文本时,它应该在web视图中打开两个不同的链接。如何实现这一点: 下面的代码我已经写:如何使UILabel文本中的两个或多个字符串指向不同的链接
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is Yahoo and Google" attributes:nil];
[attributedString addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: NSMakeRange(8,5)];
[attributedString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Helvetica" size:15]
range: NSMakeRange(8,5)];
[attributedString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Didot" size:24]
range: NSMakeRange(18,6)];
self.linkLabel.attributedText = attributedString;
}
现在我想,当用户点击Google应该打开google.com而当用户点击雅虎应该打开yahoo.com。如何可能?
答
尝试改变的UITextView,它应使用以下
let verbiage = links.text! // UITextView text
let attributes = NSMutableAttributedString(string: verbiage)
let googleRange = (verbiage as NSString).range(of: "Google")
let yahooRange = (verbiage as NSString).range(of: "Yahoo")
attributes.addAttribute(NSLinkAttributeName, value: "https://www.google.com", range: googleRange)
attributes.addAttribute(NSLinkAttributeName, value: "https://www.yahoo.com", range: yahooRange)
let linkAttributes: [String : Any] = [
NSForegroundColorAttributeName: UIColor.red,
NSUnderlineColorAttributeName: UIColor.clear,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleNone.rawValue]
links.linkTextAttributes = linkAttributes
links.attributedText = attributes
不要忘记设置滚动启用为false,并编辑为false,以获得的UITextView类似的UILabel
答
使用下面一行的分配attributedString
[attributedString addAttribute:NSLinkAttributeName value:[NSUrl [email protected]"https://www.google.com"] range:NSMakeRange(18,6)];
同样可以为其他字符串做,以及前添加链接到您的文本。
为什么不用两个按钮呢? –
使用两个彼此相邻的按钮 – FightOn
参考此链接 - https://stackoverflow.com/questions/21629784/how-to-make-a-clickable-link-in-an-nsattributedstring-for-a希望它会有用 – Chaitra