【问题标题】:self.delegate = self; what's wrong in doing that?self.delegate = 自我;这样做有什么问题?
【发布时间】:2009-11-17 10:00:22
【问题描述】:

self.delegate = self; 这样做有什么问题? 正确的做法是什么?

谢谢,尼尔。

代码:

(UITextField*)initWith:(id)sender:(float)X:(float)Y:(float)width:(float)hieght:(int)textFieldTag { 
    if (self = [super initWithFrame:CGRectMake(X, Y,width, hieght)]) {
        finalText = [[NSMutableString alloc] initWithString:@""];
        senderObject = sender;
        self.textColor = [UIColor blackColor]; 
        self.font = [UIFont systemFontOfSize:17.0]; 
        self.backgroundColor = [UIColor whiteColor]; 
        self.autocorrectionType = UITextAutocorrectionTypeNo;   
        self.keyboardType = UIKeyboardTypeDefault;     
        self.returnKeyType = UIReturnKeyDone; 
        self.clearButtonMode = UITextFieldViewModeWhileEditing;    
        self.tag = textFieldTag;        
        self.delegate = self;    
        [sender addSubview:self];
    }
    return self;
} 

注意事项:这是一个文本字段,当我将委托设置为另一个对象(self.delegate = mainView)时,一切正常,但是我必须在mainView,我想把它们放在 self(我创建的一个 uiTextField 类)中。如果我设置 self.delegate = self,我会得到一个 textField 但键盘没有出现。

【问题讨论】:

  • 请澄清:你为什么知道我错了。发生了什么
  • 嗨。这是一个文本字段,当我将委托设置为另一个对象(self.delegate = mainView)时,一切正常,但是我必须在 mainView 中实现委托方法,我想将它们放入 self(我创建的 uiTextField 类)。如果我设置 self.delegate = self,我会得到一个 textField 但键盘没有显示。
  • 在问题中添加了来自 OP 的评论。
  • UITextView 的独特之处在于无法做到这一点。解决方法很简单,stackoverflow.com/a/13338493/294884

标签: iphone uitextfield delegates self


【解决方案1】:

查看此帖

http://www.cocoabuilder.com/archive/cocoa/241465-iphone-why-can-a-uitextfield-be-its-own-delegate.html#241505

基本上,当您以自己为代表单击 UITextField 时“冻结”的原因是 respondsToSelector 正在调用自己 -> 无限递归。

UITextField 是独一无二的 AFAIK。您通常可以使用一个类作为它自己的委托,而没有特别的问题。对于 UITextField,您必须创建一个实际的委托(当然,它可以调用作为委托的 UITextField 上的方法。请注意避免保留循环,即使您使用的是 ARC)。

【讨论】:

  • 仅供参考:iOS 8 及更高版本允许 self.delegate = 自引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
相关资源
最近更新 更多