1

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
        }
nc14
  • 539
  • 1
  • 8
  • 26
  • "textViewOutlet.font": You replace the whole font. If you want to manage text with different font, use `NS(Mutable)AttributedString` and set it to `textViewOutlet.attributedText = newAttribtuedStringWithDifferentFonts` – Larme Jun 14 '19 at 10:36
  • @Larme you should type your response as an Answer since you are providing a solution :) – ekscrypto Jun 14 '19 at 11:03
  • Hi @Larme - could you elaborate on how I'd actually achieve that? Where would NSMutableAttributableString go? How would it be 'set' to the textviewOutlet? – nc14 Jun 14 '19 at 11:48
  • There are plenty of question with NSAttributedString. A first step is to understand how it works. How to apply it to target range, and then apply it with your needs. – Larme Jun 14 '19 at 11:53

0 Answers0