gpt4 book ai didi

ios - 如何在 NSAttributedString 上设置字体大小

转载 作者:IT王子 更新时间:2023-10-29 08:02:47 25 4
gpt4 key购买 nike

编辑 - 这已被标记为重复,但正如我在下面所述,我正在寻找 Swift 解决方案。我发现的所有内容都是用 Objective C 编写的。

我正在尝试将 HTML 转换为 NSAttributedString,但不知道如何设置字体样式和大小。所有示例都在我不熟练的Objective C中。如何将字体样式/大小设置为System 15(作为示例)

private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
return str
}
} catch {
}
return nil
}

编辑......我已经尝试了几种方法。我无法让它工作。我现在收到一条错误消息:没有更多上下文,表达式类型不明确。它指向 NSAttributedString我尝试了以下方法:

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
attributes: myAttribute,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

最佳答案

let myString = "Swift Attributed String"
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

字体

let myAttribute = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)! ]

阴影

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSShadowAttributeName: myShadow ]

下划线

let myAttribute = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue ]

文字颜色

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

背景颜色

let myAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]

关于ios - 如何在 NSAttributedString 上设置字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45959903/

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