问题
I have created a button that I want to check if text is selected then if so toggle bold and unbold over the selectedRange when tapped. At the moment my code will just change the selectedRange to bold and I can't undo it or check if there is a selection. How can I achieve this?
func bold() {
if let textRange = selectedRange {
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.bold)]
noteContents.textStorage.addAttributes(attributes as [NSAttributedString.Key : Any], range: textRange)
}
回答1:
This might do the trick:
func toggleBold() {
if let textRange = selectedRange {
let attributedString = NSAttributedString(attributedString: noteContents.attributedText)
//Enumerate all the fonts in the selectedRange
attributedString.enumerateAttribute(.font, in: textRange, options: []) { (font, range, pointee) in
let newFont: UIFont
if let font = font as? UIFont {
if font.fontDescriptor.symbolicTraits.contains(.traitBold) { //Was bold => Regular
newFont = UIFont.systemFont(ofSize: font.pointSize, weight: .regular)
} else { //Wasn't bold => Bold
newFont = UIFont.systemFont(ofSize: font.pointSize, weight: .bold)
}
} else { //No font was found => Bold
newFont = UIFont.systemFont(ofSize: 17, weight: .bold) //Default bold
}
noteContents.textStorage.addAttributes([.font : newFont], range: textRange)
}
}
}
We use enumerateAttribute(_:in:options:using:)
to look for fonts (since bold/non-bold) is in that attribute.
We change it according to your needs (bold <=> unbold).
来源:https://stackoverflow.com/questions/56021846/toggle-selectedrange-attributes-in-uitextview