-4

I want 2 buttons, one for bold and one for italic. When a user presses either button I want it to enable bold/italics for the text they input on the textView, how can I do this in swift?

ShedSports
  • 541
  • 2
  • 7
  • 14

2 Answers2

0

Will add two different actions for two buttons. If user click on buttons either Bold or italic bellow methods will get call & the font will get change for textView.

@objc func boldButtonAction(sender : UIButton) {
    textView.font = UIFont.boldSystemFont(ofSize: 14)
}

@objc func italicButtonAction(sender : UIButton) {
    textView.font = UIFont.italicSystemFont(ofSize: 14)
}
komara
  • 334
  • 1
  • 7
  • 1
    You can simply assign/change textview font like the above. – komara Jun 18 '19 at 04:42
  • Please add some explanation to your code such that others can learn from it - do this by editing the answer, not by putting the explanation in the comment section – Nico Haase Jun 18 '19 at 07:08
0

You can use a keyboard accessory view.

override func viewDidLoad() {
    super.viewDidLoad()

    let bar = UIToolbar()
    let boldButton = UIBarButtonItem(title: "Bold", style: .plain, target: self, action: #selector(toggleBold))
    let italicButton = UIBarButtonItem(title: "Italic", style: .plain, target: self, action: #selector(toggleItalic))
    bar.items = [boldButton, italicButton]
    bar.sizeToFit()
    textView.inputAccessoryView = bar


    guard let font = getFont() else { assert(false); return }
    textView.font = font
    textView.typingAttributes = [NSAttributedString.Key.font: font]
}

Toggle a boolean to 1 and 0 if enabled / disabled for bold and italic and update the font as:

func updateFont() -> UIFont? {
    let italic = keyboardAddon.italic
    let bold = keyboardAddon.bold
    let font = UIFont(name: "Helvetica", size: 14.0)

    if bold && italic {
        return font?.withTraits([ .traitBold, .traitItalic ])
    } else if bold {
        return font?.withTraits(.traitBold)
    } else if italic {
        return font?.withTraits(.traitItalic)
    } else {
        return font
    }
}
Herbert Bay
  • 215
  • 2
  • 15