Bal*_*yal 7 ios nsmutableattributedstring swift
我使用下面的代码来改变foreground color和font使用属性字符串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)
我遇到了同样的问题。虽然我没有使用范围来构建AttributedString
我的代码看起来像
self.contentTextLabel.attributedText = NSAttributedString(string: "content",
attributes: [.foregroundColor: UIColor.red, .background: UIColor.blue])
Run Code Online (Sandbox Code Playgroud)
运行时,背景色显示为蓝色,但前景色不显示为红色。我认为这是一个 swift 的问题,所以我也在 Objective-C 中尝试过,但仍然不起作用。
我正在使用故事板,我通过删除该标签上的命名颜色来解决这个问题。我认为这是 Apple 的错误,以某种方式在标签上设置的命名颜色覆盖了属性字符串中设置的前景色。
为了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)
参考形式: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)
看图片:
| 归档时间: |
|
| 查看次数: |
5479 次 |
| 最近记录: |