我正在对UITextView进行子类化,并在子类(如textViewDidChangeSelection
)中实现一些委托方法,但我还需要在视图控制器中获得UITextView委托的通知。因此,如果我创建子类的对象并在视图控制器中设置textview委托,则只会在视图控制器中通知委托方法,而不会在子类中通知。我需要同时通知这两个类。我使用的语言是swift 2
我试图继承子类中的UITextViewDelegate委托:
@objc protocol CustomTextViewDelegate:UITextViewDelegate {
func customTextViewDidChangeSize(chatTextView: CustomTextView)
}
然后在VC中:
let customTV = CustomTextView()
customTV.customTextViewDelegate = self
但没有调用任何textview委托方法。
3条答案
按热度按时间vfwfrxfs1#
问得好。这里有一个不太好的答案,因为它需要你重写所有的delegate-method,因此在iOS版本之间不稳定,以防delegate-method随时间变化。
在这种方法中,
ViewController
和CustomTextField
都可以访问委托事件。我们重写
delegate
,并在一个单独的变量(称为superDelegate
)中存储对它的引用。CustomTextField将其自身分配给super.delegate
,并实现UITextView-delegate
。我们必须确保每个委托事件都触发相应的superDelegate
的事件。我们的'ViewController'现在可以将自己指定为
CustomTextView
的委托:现在,
ViewController
和CustomTextField
都可以访问UITextFieldDelegate
。oxalkeyp2#
两个对象不能同时委托给
UITextView
对象。因此,您应该创建新协议(CustomTextViewDelegate
)并在其中创建委托属性。使您的ViewController
确认此CustomTextViewDelegate
并实现它的方法。在您的CustomTextView
中'UITextViewDelegate
方法的实现,您可以调用相应的CustomTextViewDelegate
方法。fwzugrvs3#
@nayooti的方法非常好。但是我必须做一些修正才能正常工作。主要的一点是一些委托方法不会被调用(例如
shouldChangeTextIn range
,因此textViewDidChange
也是)。我发现可以通过在被覆盖的
delegate
变量的get访问器上返回super.delegate
而不是superDelegate
来修复这个问题。