I'd like to have the user style a UITextView with multiple styles by selecting the range and the style. To keep it simple right now, I have a UITextView and 2 UIButtons (bold and italic), but I'd love to add multiple styles (colors, size, font weight etc).
var selectedRange: NSRange?
@IBOutlet weak var textBox: UITextView!
let boldAttribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22, weight: .bold)]
let italicAttribute = [NSAttributedStringKey.font: UIFont.italicSystemFont(ofSize: 15)]
@IBAction func pressedItalic(_ sender: UIButton) {
if selectedRange != nil {
let string = NSMutableAttributedString(string: textBox.text)
string.addAttributes(italicAttribute, range: selectedRange!)
textBox.attributedText = string
}
}
@IBAction func pressedBold(_ sender: UIButton) {
if selectedRange != nil {
let string = NSMutableAttributedString(string: textBox.text)
string.addAttributes(boldAttribute, range: selectedRange!)
textBox.attributedText = string
}
}
override func viewDidLoad() {
super.viewDidLoad()
textBox.delegate = self
}
func textViewDidChangeSelection(_ textView: UITextView) {
selectedRange = textView.selectedRange
print(selectedRange)
}
The problem: when selecting a new style, the previous selection and selected style goes back to the default. How can I add multiple different styles to one text view without refreshing it every time? My end goal is to build something similar to the prebuilt iOS notes app, where the user can fully customize the styles and layout of the text.
UPDATE:
I'd like the show the controls (buttons) to the user at all time. Is that also possible with a UIMenuController?
EDIT:
I'd love to be able to control all styles (color, font weight, size etc)
Thanks!!!