我创建了如下所示的文本视图,并添加了键盘按钮供用户更改字体。它正在工作,但是它更改了整个文本的字体,但是我只想在单击按钮后更改字体。您可以帮忙吗?
func setKeyboard() { // this is for keyboard button
let bar = UIToolbar()
let flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
let font = UIBarButtonItem(image: UIImage(named: "icons8-image-80"), style: .plain, target: self, action: #selector(fontTapped))
bar.barTintColor = UIColor(displayP3Red: 30/255, green: 30/255, blue: 30/255, alpha: 1)
bar.sizeToFit()
writePost.inputAccessoryView = bar
}
// and this one is fontTapped function
@objc func fontTapped() {
if fontTag == 0 {
let attributedText = NSMutableAttributedString(string: writePost.text, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)])
writePost.attributedText = attributedText
fontTag = 1
} else {
writePost.font = UIFont(name: "AvenirNext-DemiBoldItalic", size: 16)
fontTag = 0
}
}
您将像这样使用UITextField的attributedText属性:
并且可能在UITextFieldDelegate的shouldChangeCharactersInRange()中构建您的属性字符串,以便更改传入字符的字体。