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
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).