I'm using UIKeyCommands
to allow users with a bluetooth keyboard to use CMD + B
for bold and CMD + I
for italic.
I've managed to do this successfully here ...
@objc func boldText() {
textViewOutlet.font = UIFont(name:"Avenir-Heavy", size: 16)
}
@objc func italicText() {
textViewOutlet.font = UIFont(name:"AvenirNext-Italic", size: 16)
}
// enable functions
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "b", modifierFlags: .command, action: #selector(boldText), discoverabilityTitle: "Bold"),
UIKeyCommand(input: "i", modifierFlags: .command, action: #selector(italicText), discoverabilityTitle: "Italic")
]
}
However, when I use these key commands, it now changes the whole textview to bold or italic, instead of only the text typed before bold or italic is 'disengaged' again.
Any help much appreciated!
I think I need something like :
@objc func italicText() {
textViewOutlet.font.FROMTHECURRENTLOCATION UNTIL IT'S DISENGAGED = UIFont(name:"AvenirNext-Italic", size: 16)
}
EDIT :
On looking into this further, I see there is a method called typing attributes that I think could be used. Some detail on this answer
I have tried this :
@objc func boldText() {
textViewOutlet.typingAttributes = UIFont(name:"Avenir-Heavy", size: 16)
}
but I don't think I have the method correct. Does anyone know how to use typingAttributes to set a font?
UPDATE :
I've solved this by using .typingattributes and adapting the answer here.
You can achieve the ability for users to make text bold/italic/different colours etc from the time they pressed it by using :
@objc func boldText() {
let makeBold: [String : Any] = [
NSAttributedStringKey.font.rawValue: UIFont(name: "Avenir-Heavy", size: 15.0)!
]
textViewOutlet.typingAttributes = makeBold
}