Very simple 2023 approach.
This is a common, everyday thing and the idiom is just:
(1) Yes, you simply "keep" the delegate set by consumers in a variable:
class YourTextView: UITextView, UITextViewDelegate {
weak var outsideDelegate: UITextViewDelegate?
override var delegate: UITextViewDelegate? {
set { outsideDelegate = newValue }
get { return outsideDelegate }
}
it's that easy. And
(2) You simply set the delegate to "yourself"
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
common()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
common()
}
func common() {
super.delegate = self
}
(3) Simply go ahead and use any of "your" delegates as you wish. Note that of course, obviously, you must call on the "outside super" - assuming you want to.
(It's NOT possible to "automate" this in some way, and it would make no sense at all to do so.)
func textViewDidBeginEditing(_ textView: UITextView) {
.. some layout code, for example ..
outsideDelegate?.textViewDidBeginEditing?(textView)
}
func textViewDidChange(_ textView: UITextView) {
outsideDelegate?.textViewDidChange?(textView)
.. some layout code, for example ..
}
func textViewDidEndEditing(_ textView: UITextView) {
.. some database code, for example ..
}
As an important detail, note that you may need to call the "outside" delegate either before or after your own work. Note that, of course, this applies every single time you have ever written an iOS call (like "viewDidLoad" where you have to call super. In the three examples above the "outside" delegate is called after, before, and not at all.
Here's the whole thing to copy and paste.
class YourTextView: UITextView, UITextViewDelegate {
weak var outsideDelegate: UITextViewDelegate?
override var delegate: UITextViewDelegate? {
set { outsideDelegate = newValue }
get { return outsideDelegate }
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
common()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
common()
}
func common() {
super.delegate = self
}
.. your delegate calls go here ..
.. you must (of course) call the outsideDelegate as you see fit ..
}
Again - there is NO WAY to "automate" calling the consumer delegates. It would make no sense at all to try to do so. You just call them in "your" degelates, if relevant and as you see fit. Exactly as in the million times you have called "super. ..." in iOS code. It makes absolutely no sense to say "oh you may forget to do it". Any of the million times you have had to type "super. ..." in iOS, you may have forgotten to do it! There is nothing "automatic" about it, it's a decision based on the code being written where/how "super. ..." is called.