使用 typingAttributes 更改下一段的样式

changing the style of next paragraph using typingAttributes

我正在开发 iOS 应用程序。在应用程序中,我有一个 UITextView 用户应该在其中键入一些属性文本的段落。我的要求是每次用户点击 Enter.

时更改下一段的样式

因此,我实现了以下 TextView Delegate 函数:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if (text == "\n") {
        textView.typingAttributes = [NSMutableAttributedString.Key.paragraphStyle: self.paragraphStyle]
    }
    return true
}

问题是:

下一段的样式已更改,但不是在按 Enter 后立即更改。相反,首先返回一个带有旧样式的新行,当用户再次按下 Enter 时,段落样式会更改。

示例:

完整代码:

import UIKit

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var textView: UITextView!    
    // Create paragraph styles
    let paragraphStyle = NSMutableParagraphStyle()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
        
        // Create paragraph style
        self.paragraphStyle.firstLineHeadIndent = 140
        // Create attributed string
        let string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
        // Create attributed string
        let myAttrString = NSMutableAttributedString(string: string, attributes: [:])
        // Write it to text view
        textView.attributedText = myAttrString
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            textView.typingAttributes = [NSMutableAttributedString.Key.paragraphStyle: self.paragraphStyle]
        }
        return true
    }
}

我认为 shouldChangeTextIn 的工作方式类似于拼写检查器或自动更正的工作方式。当您第一次输入拼写错误的单词时,它不会被替换,直到您按下 space 栏。类似地,shouldChangeTextIn 在您输入时最初确认 \n,但在输入以下内容之前不会发生替换。

您可以改用 textViewDidChange 实例方法,它来自相同的 UITextViewDelegate 协议:

func textViewDidChange(_ textView: UITextView) {
    if (textView.text.last == "\n") {
        textView.typingAttributes = [NSMutableAttributedString.Key.paragraphStyle: self.paragraphStyle]
    }
}