文本视图中的Swift常规字体和粗体字体

问题描述

我正在尝试在textview中一起使用常规字体和粗体字体。用户键入时,用户可以键入常规字体,或者(有一个按钮可以写粗体),用户可以点击按钮来键入粗体。用户如何在同一textview中键入常规字体和粗体字体?我可以使用哪种方法

这就是我想要的:

example

这是我的代码

func textViewDidChangeSelection(_ textView: UITextView) {
    
    var partOne = NSMutableAttributedString()
    var partTwo = NSMutableAttributedString()
    
    let boldFontAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.black,.font: UIFont.boldSystemFont(ofSize: 17)]
    let normalFontAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.darkGray,.font: UIFont.systemFont(ofSize: 15)]
    let combination = NSMutableAttributedString()
    
    if boldButtonTap == false {
        partOne = NSMutableAttributedString(string: textView.text,attributes: normalFontAttributes)  
    } else {
        partTwo = NSMutableAttributedString(string: textView.text,attributes: boldFontAttributes)    
    }
    combination.append(partOne)
    combination.append(partTwo)
    textView.attributedText = combination
}

解决方法

var normalText = "normal text" 
var boldText  = "bold text" 
var attributedString = NSMutableAttributedString(string:normalText)
let textField = UITextField()

var attrs = [NSAttributedString.Key.font : UIFontDescriptor.SymbolicTraits.contains(.traitBold)]
var boldString = NSMutableAttributedString(string: boldText,attributes:attrs)

attributedString.append(boldString)

// for normal text
textField.text = normalText
// for normal text with bold
textField.attributedText = attributedString
,

您需要使用文本字段的attributedText属性将其内容设置为样式文本。 (attributedText属性采用类型为NSAttributedString的值 创建一个文本编辑器以使用户将样式应用于文本视图的内容是一项艰巨的任务,这超出了SO答案的范围。

(请注意,UITextField也具有typingAttributes之类的属性,可让您更改用于输入新文本的属性。如果用户在输入新文本之前将字体设置为粗体,则可以使用该属性。)