swift - 使用 attributedText 在 UITextView 中实现撤消和重做

标签 swift uitextview nsattributedstring undo redo

我正在尝试将撤消重做 功能添加到我的UITextView 实现中。我使用的是 attributedText 而不仅仅是 UITextViewtext 属性。我尝试使用 undoManager 中的函数调用,如 Apple documentation 中引用的那样,但是似乎什么也没有发生。令我惊讶的是,我无法通过谷歌搜索找到有关该主题的任何内容。在使用 attributedTextUITextView 实现撤消和重做之前,有没有人遇到过这个问题/知道如何解决这个问题?

示例代码

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

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

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

最佳答案

下面是一些示例代码,用于处理 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()            
    }
}

显然,您需要在 Storyboard中连接 Action /导出和 TextView 的委托(delegate)导出

关于swift - 使用 attributedText 在 UITextView 中实现撤消和重做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528946/

相关文章:

ios - 在 Swift for Mac 上,BLE 的数据类型转换

Swift4,如何通过单击在当前 View Controller 的 subview 中以编程方式创建的按钮来呈现另一个 View Controller

swift - 隐藏键盘加回车键?

ios - 在 UITextView 上打字时按下返回按钮时有没有办法触发函数?

ios - 如何执行退格和删除?

ios - 向 NSAttributedString 添加左边距的最佳方法是什么?

ios - 从中间截断 NSString 的子字符串

swift - 设置前景色仅对 NSAttributedString 有效一次

ios - 如何将 UIColor 转换为 UInt32 ?我收到错误 Ambiguous use of operator "+="

xcode - 以编程方式打开通知中心/今日 View