如何在UILabel文本中创建两个或多个字符串指向不同的链接

时间:2017-08-07 17:15:07

标签: ios objective-c uilabel xcode8.2

我有一个显示字符串的UILabel。我需要更改UILabel中特定文本的颜色,当点击这些文本时,它应该在webview中打开两个不同的链接。如何实现这个目标: 我写的代码如下:

  - (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.com,当用户点击雅虎时它应该打开yahoo.com。怎么可能?

2 个答案:

答案 0 :(得分:2)

尝试更改为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

不要忘记将Scrolling设置为false并将Editable设置为false以使UITextView与UILabel类似

答案 1 :(得分:1)

在分配referencedString

之前,使用以下行添加指向文本的链接
 [attributedString addAttribute:NSLinkAttributeName value:[NSUrl urlwithString@"https://www.google.com"] range:NSMakeRange(18,6)];

同样,你也可以为其他字符串做。