【问题标题】:UITextView : the foregroundColor of link attributes dont change (NSAttributedStringKey)UITextView:链接属性的前景颜色不变(NSAttributedString Key)
【发布时间】:2018-04-03 20:39:17
【问题描述】:

NSAttributedStringKey 和 UITextView 有问题

事实上,我正在尝试这样做:

这是理论上应该可以工作的代码

class ViewController: UIViewController,UITextViewDelegate {
 @IBOutlet weak var txtView: UITextView!
 override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self;
    let linkAttributes : [NSAttributedStringKey : Any] = [
            .link: URL(string: "https://exemple.com")!,
            .font:UIFont.boldSystemFont(ofSize: 18),
            .foregroundColor: UIColor.blue] ;
    let attributedString = NSMutableAttributedString(string: "Just 
     click here to do stuff...")
    attributedString.setAttributes(linkAttributes, range: 
    NSMakeRange(5, 10))
     txtView.attributedText = attributedString;
}}

但是这段代码显示了这个

所以我尝试通过添加两行额外的代码来解决问题:

 let linkAttributes : [NSAttributedStringKey : Any] = [
            .link: URL(string: "https://exemple.com")!,
            .font:UIFont.boldSystemFont(ofSize: 18),
            .foregroundColor: UIColor.blue,
            .strokeColor : UIColor.black,//new line
            .strokeWidth : -1,//new line
           ] ;

不幸的是,显示不是我想要的。

有人帮我解决这个问题,我搜索了互联网但一无所获。

提前致谢

INFO:我为该出版物拍摄的第一张图片 :Link in UITextView not working in Swift 4

【问题讨论】:

    标签: swift xcode textview swift4 nsattributedstring


    【解决方案1】:

    似乎“.link”使用了 UITextView 的 tintColor。尝试设置 tintColor...

    【讨论】:

      【解决方案2】:

      我让您的代码只需稍加调整即可工作:

      override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
      
          let basicAttributes : [NSAttributedStringKey : Any] = [
              .font: UIFont.systemFont(ofSize: 18),
              .foregroundColor: UIColor.black]
          let linkAttributes : [NSAttributedStringKey : Any] = [
              .link: URL(string: "https://www.stackoverflow.com")!,
              .font:UIFont.boldSystemFont(ofSize: 18),
              .foregroundColor: UIColor.blue]
          let attributedString = NSMutableAttributedString(string: "Just click here to do stuff...", attributes: basicAttributes)
          attributedString.addAttributes(linkAttributes, range: NSMakeRange(5, 10))
          textView.attributedText = attributedString
      }
      

      您可能注意到我为整个字符串设置了字体(这可能不是必需的,尤其是如果您已经在 XIB 或情节提要中设置了 UITextView 对象的字体),但我猜真正的解决方案是使用 @987654322 @,它将链接属性添加到属性字符串中的其他属性。

      【讨论】:

      • 很抱歉我的答案迟到了,我试过了,但它不起作用。它没有显示要单击的文本。
      • 在 iOS
      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 2011-10-07
      • 1970-01-01
      相关资源
      最近更新 更多