Hamster
Hamster

Reputation: 375

How do I make UITextView use its parent's undoManager instead of its own

I have a UIViewController that has a PKCanvasView and several UITextViews as its subviews. I need to unify all of these views' undo managers, so I can control them as a single undo stack from my view controller.

I can already do this with PKCanvasView, it seems that by default it uses the undoManager of its parent view, so I can do things like manually register undo events from my view controller, and undo/redo them from my PKCanvasView's PKToolPicker's undo/redo buttons, which is fantastic.

Regrettably, this doesn't seem to be the case with UITextView, each one seems to have its own undoManager, and it doesn't connect in any way with my control view's undo manager, which is a big problem.

Anyone know how can I force a UITextViews to use a view controller's undo manager?

Thanks!

Upvotes: 2

Views: 113

Answers (1)

Franklyn Oreben
Franklyn Oreben

Reputation: 358

The best way to achieve this is to create an extension UITextView and set the undoManager of the UITextView instance to its parent's undoManager:

extension UITextView {
    
    override open func awakeFromNib() {
        self.undoManager = (self.superview as? UIViewController)?.undoManager
    }
}

The awakeFromNib method is a UIView initializer that gets called after it has been loaded from a xib or storyboard. This will ensure that every instance of UITextView in your view controller will have its undoManager set to the view controller's undoManager.

Upvotes: 0

Related Questions