gpt4 book ai didi

swift - 向 NSMutableAttributedString 添加几个属性

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:45 24 4
gpt4 key购买 nike

我正在尝试向 NSMutableAttributedString 添加几个属性;我试过这个:

let stringNumero: NSString = "\(squadra.cori.count)" //= two-digit number
var stringNumeroMutable = NSMutableAttributedString()
stringNumeroMutable = NSMutableAttributedString(string: stringNumero as! String, attributes: [NSFontAttributeName: UIFont(name: "Noteworthy-Light", size: 9)!,
NSForegroundColorAttributeName: UIColor(red: 110/255.0, green: 183/255.0, blue: 93/255.0, alpha: 1.0)])
cell.numeroCori.attributedText = stringNumeroMutable

现在我想添加其他属性,我将使用此代码:

stringNumeroMutable.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(8), range: NSRange(location: 0, length: 1))

但是我遇到了一个问题:

enter image description here

如您所见,粗体效果仅归因于第一个数字,之前的归因(例如字体)消失了。我认为第二个 NSFontAttributedName 订阅了前一个,那么有没有办法同时设置字体和粗体?非常感谢!!!

编辑:按照建议我试着记忆这样的方法:

let stringNumero: NSString = "\(squadra.cori.count)" //= two-digit number
var stringNumeroMutable = NSMutableAttributedString()
stringNumeroMutable = NSMutableAttributedString(string: stringNumero as! String, attributes: [NSFontAttributeName: UIFont(name: "Noteworthy-Light", size: 9)!,
NSForegroundColorAttributeName: UIColor(red: 110/255.0, green: 183/255.0, blue: 93/255.0, alpha: 1.0)])
cell.numeroCori.attributedText = stringNumeroMutable

stringNumeroMutable.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(9), range: NSRange(location: 0, length: stringNumeroMutable.length))

cell.numeroCori.atributedText = stringNumeroMutable

但是第二次调用覆盖了第一次调用(因此数字失去了属性字体)。如何解决?

enter image description here

最佳答案

我认为你的问题是你使用方法 boldSystemFontOfSize

boldSystemFontOfSize:

Returns the font object used for standard interface items that are rendered in boldface type in the specified size.

查看我的解决方案:

@IBOutlet weak var label: UILabel!
var mutableAttributedString: NSMutableAttributedString!
override func viewDidLoad() {
super.viewDidLoad()
let someString = "Hello World"
let attr: [String: AnyObject] = [NSFontAttributeName: UIFont(name: "Helvetica", size: 10)!,
NSForegroundColorAttributeName: UIColor(red: 0.18, green: 0.18, blue: 0.18, alpha: 1.0)]
mutableAttributedString = NSMutableAttributedString(string: someString, attributes: attr)
label.attributedText = mutableAttributedString
}

@IBAction func buttonPressed(sender: UIButton) {
let font = mutableAttributedString.attribute(NSFontAttributeName, atIndex: 1, effectiveRange: nil)!
mutableAttributedString.addAttribute(NSFontAttributeName, value: font.fontWithSize(20) , range: NSMakeRange(0, mutableAttributedString.length))
label.attributedText = mutableAttributedString
}

buttonPressed 函数中,您定义 mutableAttributedString 的当前字体,然后您可以使用方法 fontWithSize 更改字体的大小。

关于swift - 向 NSMutableAttributedString 添加几个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32093342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com