我创建了一个包装UITextView并添加一些ui元素的类.我希望新类’API与UITextView相同,因此我使用消息转发(下面列出)在包装文本视图和委托之间中继消息.
令人恼火的是,编译器会在转发类的实例上发出方法调用警告.例如,将为以下行生成错误:
[aMyTextView setContentOffset:CGPointZero animated:YES];
所以我被迫为这些方法声明并创建“手动转发”实现,这违背了使用消息转发的整个目的.
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated { [_textView setContentOffset:contentOffset animated:animated]; }
我知道解决这个问题的通常方法是使用performSelector:方法之一,但这是一个麻烦的,当一些参数不是NSObjects时(虽然Erica Sadun’s extensions是一个很大的帮助),b)再次,完全违背了创建一个透明的包装器.
(子类化UITextView也是不可能的,因为我需要在文本视图下面插入视图.)
有办法解决这个问题吗?
列出该类的所有相关部分:
@interface MyTextField : UIView<UITextViewDelegate> { UIImageView* _border; UITextView* _textView; UIButton* _clearButton; NSObject<UITextViewDelegate>* _delegate; } @implementation MWTextField . . . // Forwards messages in both directions (textView <--> delegate) #pragma mark Message forwarding // Protocol messages will only be sent if respondsToSelector: returns YES - (BOOL)respondsToSelector:(SEL)aSelector { if ([_delegate respondsToSelector:aSelector]) return YES; else return [super respondsToSelector:aSelector]; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { // First,try to find it in the UITextView if ([_textView respondsToSelector:selector]) { return [_textView methodSignatureForSelector:selector]; } // Then try the delegate else if ([_delegate respondsToSelector:selector]) { return [_delegate methodSignatureForSelector:selector]; } else { return [super methodSignatureForSelector: selector]; } } - (void)forwardInvocation:(NSInvocation *)invocation { SEL aSelector = [invocation selector]; if ([_textView respondsToSelector:aSelector]) { [invocation invokeWithTarget:_textView]; } else if ([_delegate respondsToSelector:aSelector]) { [invocation invokeWithTarget:_delegate]; } else { [self doesNotRecognizeSelector:aSelector]; } } . . . @end
解决方法
声明一个类别,该类别提供您要转发的方法的方法声明:
@interface MyTextField (ImGonnaLetYouFinishButFirstImForwardingThese) ... methods you want to forward here ... @end
无需提供@implementation.
请注意,这是一种相当不典型的模式.不公平,非常.应该没有理由不能进行子类化.你说Subclassing UITextView也是不可能的,因为我需要在文本视图下面插入视图,但事实并非如此.
If I subclass UITextField,all I can
do with the other views is to add them
as subviews,which means they will be
on top of the text field. I guess I
could modify drawRect:… Is that what
you would suggest? Or what do you have
up your sleeve there?
如果需要组,请创建一个UIView子类,该子类适当地管理各种子视图,不需要转发.然后你可以随意订购视图.
很少使用转发.沿着这条路走下去就是疯狂.这听起来好像你的设计有点杂草,但没有足够的信息来真正说出更具体的信息.