How to implement undo/redo with programatic change of the textValue of a NSTextView?

后端 未结 3 2151
日久生厌
日久生厌 2021-02-20 15:34

I created a simple demo app with a NSTextView and a button, the provided a NSTextViewDelegate to the textView and added an action:

- (IBAction)actionButtonClicke         


        
3条回答
  •  遇见更好的自我
    2021-02-20 15:53

    Let's say you want your NSTextView to create a new undo group when user hits the Enter key (Apple Pages behavior). Then you might type this code in your NSTextView subclass:

    override func shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) -> Bool {
        super.shouldChangeTextInRange(affectedCharRange, replacementString: replacementString)
        guard replacementString != nil else { return true }
    
        let newLineSet = NSCharacterSet.newlineCharacterSet()
        if let newLineRange = replacementString!.rangeOfCharacterFromSet(newLineSet) {
    
            // check whether it's a single character (user hit Return key)
            let singleCharRange = (replacementString!.startIndex)! ..< (replacementString!.startIndex.successor())!
            if newLineRange == singleCharRange {
                self.breakUndoCoalescing()
            }
        }
    
        return true
    }
    

提交回复
热议问题