我编写了一些代码来使字符串粗体、斜体、下划线和删除。
但是,在执行这些功能时,我希望保持特定的字体名称和大小不变,而不是将其默认为字体名称和字体大小的系统值。我怎样才能做到这一点?
下面是为粗体、斜体、下划线和划线添加的代码:
if textBold == true {
let string = text
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: 25)
]
let attributedString = NSAttributedString(string: string, attributes: attributes)
modifiedString = attributedString
text_View.attributedText = modifiedString
text_View.sizeToFit()
databaseHandlerObj.editLabelData(textProjectId: fetchTextProjectId, text_Id: fetchTextId, text: modifiedString.string)
}
if textItalic == true {
text_View.sizeToFit()
let string = text
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.italicSystemFont(ofSize: CGFloat(fontSize))
]
let attributedString = NSAttributedString(string: string, attributes: attributes)
self.modifiedString = attributedString
text_View.attributedText = modifiedString
databaseHandlerObj.editLabelData(textProjectId: fetchTextProjectId, text_Id: fetchTextId, text: modifiedString.string)
}
if textUnderline == true {
text_View.sizeToFit()
let string = text
let attributedString = NSMutableAttributedString.init(string: string)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range:
NSRange.init(location: 0, length: attributedString.length))
self.modifiedString = attributedString
text_View.attributedText = modifiedString
databaseHandlerObj.editLabelData(textProjectId: fetchTextProjectId, text_Id: fetchTextId, text: modifiedString.string)
}
if textStrikethrough == true {
text_View.sizeToFit()
let string = text
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: string)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
self.modifiedString = attributeString
text_View.attributedText = modifiedString
databaseHandlerObj.editLabelData(textProjectId: fetchTextProjectId, text_Id: fetchTextId, text: modifiedString.string)
}
发布于 2021-12-14 06:24:16
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name: "name of your font", size: 12.0)]
或者创建UIFont
的扩展
extension UIFont {
class func customFont(size: CGFloat) -> UIFont {
guard let font = UIFont(name: "font name", size: 12.0) else {
return UIFont.systemFont(ofSize: 12.0)
}
return font
}
}
用它就像:
let attributedString = NSAttributedString(string: string, attributes: [NSAttributedString.Key.font: UIFont.customFont(size: 12.0)])
https://stackoverflow.com/questions/70344421
复制相似问题