属性字符串前景色在 Swift 中不起作用

Bal*_*yal 7 ios nsmutableattributedstring swift

我使用下面的代码来改变foreground colorfont使用属性字符串Swift。但是字体完美地改变没有任何问题,但foreground color没有改变

var checklistText = NSMutableAttributedString()
        checklistText = NSMutableAttributedString(string: "\(lblChecklistName.text!),\(checklistName)")
        checklistText.addAttribute(NSFontAttributeName,
                                   value: UIFont(
                                    name: "Helvetica",
                                    size: 11.0)!,
                                   range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()))
        checklistText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()+1))
        lblChecklistName.attributedText = checklistText
Run Code Online (Sandbox Code Playgroud)

sbh*_*hbs 7

我遇到了同样的问题。虽然我没有使用范围来构建AttributedString 我的代码看起来像

self.contentTextLabel.attributedText = NSAttributedString(string: "content",
                                                            attributes: [.foregroundColor: UIColor.red, .background: UIColor.blue])
Run Code Online (Sandbox Code Playgroud)

运行时,背景色显示为蓝色,但前景色不显示为红色。我认为这是一个 swift 的问题,所以我也在 Objective-C 中尝试过,但仍然不起作用。

我正在使用故事板,我通过删除该标签上的命名颜色来解决这个问题。我认为这是 Apple 的错误,以某种方式在标签上设置的命名颜色覆盖了属性字符串中设置的前景色。

  • “我正在使用故事板,并通过删除该标签上的指定颜色集解决了这个问题。我认为这是 Apple 的错误,以某种方式在标签上设置的命名颜色覆盖了属性字符串中设置的前景色。`是的,这是苹果错误,并且对于 Xcode 版本 11.3.1 仍然是一个问题。从代码中设置颜色很好,但是从情节提要中设置“命名颜色”会破坏属性文本中的前景色。请注意,从故事板设置系统颜色效果很好(自定义资产目录颜色会出现错误)。 (3认同)

Vad*_* F. 5

为了foregroundColor工作,您需要将 设置.strokeWidth为负数:

let attributes : [ NSAttributedString.Key : Any ] = [.font : UIFont(name: "Helvetica", size: 11.0),
                                                             .foregroundColor : UIColor.red,
                                                             .strokeWidth : -5]
        let stringWithAttributes = NSAttributedString(string: "YOUR STRING", attributes: attributes)
Run Code Online (Sandbox Code Playgroud)


Kir*_*odi 0

参考形式:NSMutableAttributedString

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString as 
String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
            myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:2))
lbl_First.attributedText = myMutableString
Run Code Online (Sandbox Code Playgroud)

看图片:

在此输入图像描述