【问题标题】:Objective-c overriding delegate with its descendant typeObjective-c 覆盖委托及其后代类型
【发布时间】:2012-06-12 11:38:34
【问题描述】:

我的单元格中有 textView,有时在 tableView 滚动期间会发生一些奇怪的调用。系统让我的 textView 成为第一响应者。我发现这些调用有不良行为:

#0 -[UITextView canBecomeFirstResponder] ()
#1 -[UIView(Hierarchy) deferredBecomeFirstResponder] ()
#2 -[UIView(Hierarchy) _promoteDescendantToFirstResponderIfNecessary] ()

我不知道为什么要调用它们,所以我尝试通过扩展 UITextView 并覆盖 - canBecomeFirstResponder 来解决这个问题。

这是我的 .h:

#import <UIKit/UIKit.h>

@protocol TextViewDelegate;

@interface TextView : UITextView

@property (nonatomic, assign) id<TextViewDelegate> delegate;

@end

@protocol TextViewDelegate <UITextViewDelegate>

- (BOOL)canBecomeFirstResponder:(TextView *)textView;

@end

还有.m:

#import "TextView.h"

@implementation TextView

@synthesize delegate;

- (BOOL)canBecomeFirstResponder
{
    return [self.delegate respondsToSelector:@selector(canBecomeFirstResponder:)] ? [self.delegate canBecomeFirstResponder:self] : NO;
}

@end

此解决方案有效,但在@property (nonatomic, assign) id&lt;TextViewDelegate&gt; delegate; 线上我收到了警告,但我不知道为什么。上面写着Property type 'id&lt;TextViewDelegate&gt;' is incompatible with type 'id&lt;UITextViewDelegate&gt;' inherited from 'UITextView'

如果我不这样做,为什么系统要让 textView 成为第一响应者?为什么我会收到此警告?有比我更好的解决方案吗?

【问题讨论】:

    标签: objective-c ios cocoa-touch delegates first-responder


    【解决方案1】:

    我不确定,但我怀疑这个警告是因为预编译器知道TextViewDelegate,但它还不知道这个协议正在继承UITextView 协议。只需在上面这样声明:

    @class TextView;
    
    @protocol TextViewDelegate <UITextViewDelegate>
    
    - (BOOL)canBecomeFirstResponder:(TextView *)textView;
    
    @end
    
    @interface TextView : UITextView
    
    @property (nonatomic, assign) id<TextViewDelegate> delegate;
    
    @end
    

    但我不确定我是否理解这个问题。 你有一张桌子,在一个/多个/每个单元格中都有一个UITextView,对吗? 您希望文本视图可编辑吗? 因为你可以简单地设置[textView setEditable:FALSE];

    希望这会有所帮助。

    问候,

    乔治

    【讨论】:

    • 我曾尝试设置此可编辑属性,但它也有inputAccessoryView,所以当它成为第一响应者时,inputAccessoryView 会显示。我只想控制成为这个对象的第一响应者。无论如何,你的答案是正确的。带有不知情的预编译器的东西是可耻的......
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2011-04-12
    相关资源
    最近更新 更多