我有一個需要在其上設定屬性的字串。屬性(粗體、斜體、洗掉線、下劃線)被單獨添加,但它們沒有與字串保持完整。我想知道如何使用字串保持不同的屬性完整,然后根據需要將它們一一洗掉。
Bold -
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)
}
Italic -
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)
}
Underline -
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)
}
Strikethrough -
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)
}
uj5u.com熱心網友回復:
在屬性字典上添加條件。
let string = text
var attributes: [NSAttributedString.Key: Any] = [:]
if bold {
attributes[.font] = UIFont.boldSystemFont(ofSize: 25)
}
if italic {
attributes[.font] = UIFont.italicSystemFont(ofSize: CGFloat(fontSize))
}
if underline {
attributes[.underlineStyle] = 1
}
let attributedString = NSAttributedString(string: string, attributes: attributes)
// Other Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/384882.html
