【问题标题】:Redo not working in UndoManager in swift重做在 swift 中无法在 UndoManager 中工作
【发布时间】:2019-01-10 03:57:58
【问题描述】:

我正在我的代码中实现撤消/重做功能,但由于某种原因,我的重做功能无法正常工作,这是我的文本视图代码:

  func textViewDidBeginEditing(_ textView: UITextView) {
    if descBox.textColor == .lightGray {
        DescriptionCell.descPlaceholder = descBox.text
            let descText = descBox.text
            undoManager?.registerUndo(withTarget: self, handler: {
            (targetSelf) in
            targetSelf.descBox.text = descText
            targetSelf.descBox.textColor = .lightGray
        })
        descBox.text = nil
        descBox.textColor = .black
    }
}

func textViewDidEndEditing(_ textView: UITextView) {
    if descBox.text.isEmpty {
        descBox.text = DescriptionCell.descPlaceholder
        descBox.textColor = .lightGray
    }
        let descText = descBox.text
        undoManager?.registerUndo(withTarget: self, handler: {
            (targetSelf) in
            targetSelf.descBox.text = descText
        })
        }

然后我将它用于我的 ViewController 工具栏:

@objc func Undo() {
 undoManager?.undo()
}

@objc func Redo() {
 undoManager?.redo()
}

然后在viewDidLoad中:

let undoKeyboard = UIBarButtonItem(image: UIImage(named: "Image-2"), style: .plain, target: self, action: #selector(Undo))
    undoKeyboard.tintColor = .lightGray
let redoKeyboard = UIBarButtonItem(image: UIImage(named: "Image-1"), style: .plain, target: self, action: #selector(Redo))
    redoKeyboard.tintColor = .green

【问题讨论】:

    标签: ios swift xcode undo-redo nsundomanager


    【解决方案1】:

    这里的问题:

    func textViewDidEndEditing(_ textView: UITextView) {
        if descBox.text.isEmpty {
            descBox.text = DescriptionCell.descPlaceholder
            descBox.textColor = .lightGray
        }
    
        let descText = descBox.text // <== Incorrect; Text has been set
        undoManager?.registerUndo(withTarget: self, handler: { (targetSelf) in
            // Here it means to reset the text (which already set in textDidEnd), thus meaningless (unless you made changes somewhere else and want to reset to the set text, which I assume is not what you want to achieve here)
            targetSelf.descBox.text = descText
        })
    }
    

    您在此处写的是使用一组文本注册撤消管理器(textViewDidEndEditing 表示该字段已更改,因此 descBox.text 已更新)。

    我建议您将其更改为textViewDidBeginEditing(_:) 并在那里注册撤消管理器。示例:

    func textViewDidBeginEditing(_ textView: UITextView) {
    
        let descText = descBox.text
        undoManager?.registerUndo(withTarget: self, handler: { (targetSelf) in
            targetSelf.descBox.text = descText
            targetSelf.descBox.resignFirstResponder()
        })
    }
    

    在那里,当您按下撤消时,它将设置先前的文本(在任何更改之前)并辞去第一响应者(a.k.a endEditing()

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多