代码之家  ›  专栏  ›  技术社区  ›  cdub

nsmutableAttributedString文本颜色工作不正常

  •  -1
  • cdub  · 技术社区  · 6 年前

    我有以下SWIFT 4.1代码:

        let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time");
    
        timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length));
        timeduration.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range: NSRange(location: 0, length: timeduration.length));
        timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount));
        timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2));
    

    我使用的是Swift3,并使用Xcode的工具迁移到Swift4.1,但前景颜色似乎不起作用。xcode工具“fix”添加了kct代码。不过,字体名称和大小似乎起作用。

    3 回复  |  直到 6 年前
        1
  •  0
  •   Pang abielita    6 年前

    这是解决你问题的方法。在swift 4.0及更高版本中,有一个名为nsattributedStringKey的结构,它定义字符串属性的键。

    let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time")
    
    timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length))
    
    timeduration.addAttribute(NSAttributedStringKey.foregroundColor, value: 
    
    UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range: 
    NSRange(location: 0, length: timeduration.length))
    
    timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount))
    
    timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2))
    
        2
  •  0
  •   BinaryGuy    6 年前

    修理工给了你错误的钥匙。你想用这样的东西来代替:

    timeduration.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: timeduration.length))
    

    其他人也一样。

    您使用的键用于较低级别的核心文本内容。

        3
  •  0
  •   user9483522    6 年前

    你可以这样做,我希望问题能得到解决:

    let label = UILabel()
    let labelText = "String Text"
    
    let strokeTextAttributes = [
         NSAttributedStringKey.strokeColor : UIColor.black,
         NSAttributedStringKey.foregroundColor : UIColor.white,
         NSAttributedStringKey.strokeWidth : -2.0,
         NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
       ] as [NSAttributedStringKey : Any]
    
    label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)