使用 attributeText 在 UITextView 中实现撤消和重做

Ant*_*ear 4 undo redo uitextview nsattributedstring swift

我正在尝试将撤消重做功能添加到我的UITextView. 我使用的attributedText不仅仅是text的属性UITextView我已经尝试使用Apple 文档undoManager中引用的函数调用,但是似乎没有任何反应。我很惊讶我无法通过谷歌搜索找到任何有关该主题的信息。有没有人在 / 上实现撤消和重做之前遇到过这个问题/知道如何解决这个问题?UITextViewattributedText

示例代码

textView.attributedText = NSMutableAttributedString(string: "SOME TEXT")

@objc func undo(_ sender: UIButton) {
    textView.undoManager?.undo()
}

@objc func redo(_ sender: UIButton) {
    textView.undoManager?.redo()
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*lls 7

下面是一些处理撤消/重做的示例代码UITextView。不要忘记在最初和每次更改文本后更新撤消/重做按钮的状态。

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var undoButton: UIButton!
    @IBOutlet weak var redoButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateUndoButtons()
    }

    @IBAction func undo(_ sender: Any) {
        textView.undoManager?.undo()
        updateUndoButtons()
    }

    @IBAction func redo(_ sender: Any) {
        textView.undoManager?.redo()
        updateUndoButtons()
    }

    func updateUndoButtons() {
        undoButton.isEnabled = textView.undoManager?.canUndo ?? false
        redoButton.isEnabled = textView.undoManager?.canRedo ?? false
    }
}        

extension ViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        updateUndoButtons()            
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,您需要在故事板中连接操作/出口和文本视图的委托出口