如何从光标点开始更改文本视图中的字体样式,而不是整个文本视图 - Swift

How to change font style in textview from cursor point onwards, not entire textview - Swift

我正在开发准系统文本编辑器,但 运行 遇到了一个问题。我在应用程序的顶部有两个按钮:粗体和斜体。虽然我已经想出如何让这些按钮改变输入到文本视图中的文本,但它们会改变视图中写入的所有内容,包括已经写入的内容。因此,点击“斜体”将使视图中的 所有内容 变为斜体。我想要更多“我正在打斜体 - 哦酷现在我用斜体写。现在我再次打它 - 它又正常了."

我知道这个问题是由于按钮改变了整个视图使用的字体,我只是想不出正确的方法。

到目前为止,这是我的代码:

@IBAction func italicizeHit(_ sender: Any) {
        if isItalics == false {
            textView.font = UIFont.italicSystemFont(ofSize: 15)}
        else{
            isItalics == false;
            textView.font = UIFont.systemFont(ofSize: 15)
        }
    }

我也不太清楚要将 textView.font 设置为什么才能 return 使其恢复正常状态,但这是一个更次要的问题。我最感兴趣的是正确切换斜体。

这里的问题是 textView.font 将所有 textView 的文本设置为 属性。

为了实现多种样式,您将需要使用 NSAttributedString(它可以在同一个字符串中存储粗体、斜体和常规文本),而不仅仅是一个普通的字符串。

好消息,textView 可以轻松地使用 NSAttributedString 而不是常规字符串。要更改属性,请使用 textView 的 typingAttributes 属性。这将更改任何新键入文本的样式,而不是整个 textView。这是一个例子:

class ViewController: UIViewController {

    let textView: UITextView  // initialize textView either via storyboard or code
    let attributesBold = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .bold)]
    let attributesNormal = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .regular)]
    
    override func viewDidLoad() {
        textView.attributedText = NSAttributedString(string: "")
        textView.typingAttributes = attributesNormal
    }

    @IBAction func boldTapped(_ sender: Any) {
        textView.typingAttributes = attributesBold
    }
}