代码之家  ›  专栏  ›  技术社区  ›  new2ios xav xav

自定义UITextField委托设置为自启动无限循环

  •  2
  • new2ios xav xav  · 技术社区  · 10 年前

    我正在编写iPhone应用程序,其中需要自定义UITextField类。对于我的文本字段,我需要缩进、文本前的图像和最大字符。因此,我基于UITextField创建了自定义类。我的所有文本字段都将基于这个新类。我用谷歌搜索了Stackoverflow,我发现在像我这样的情况下,我必须使用 self.delegate = self; init 所以我不需要实现像 textFieldShouldBeginEditing textFieldShouldEndEditing 在我的View Controller类中。我的所有文本字段都将在情节提要中创建,因此 initWithCoder 结果,在键入1、2或3个符号后,我收到无限循环和应用程序崩溃(此时我使用模拟器)。有趣的是,对于数字键盘或密码键盘,没有这样的问题。另外,如果我在Mac键盘上键入符号而不是在模拟器上键入符号,则没有问题。我试着调试,但在崩溃期间,它直接跳到循环中并存在错误。 如何克服这个问题?

    P.S.我问 question 当我收到无限循环时 self.delegate=自身; 可以导致这种循环,但我看到这种说法被广泛使用。可能我做得不正确,但我不知道如何使用UITextField创建可重用类。

    编辑: 这是我的代码:

    在初始化和设置边框颜色时:

    - (id)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if (self) {
    
            self.layer.borderColor=[[UIColor blackColor] CGColor];
            self.delegate = self;
        }
        return self;
    }
    

    当我开始编辑时,我更改边框颜色并设置缩进(缩进集将在属性setter中移动):

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
        // Change border of text field that is editing to orange
        textField.layer.masksToBounds=YES;
        textField.layer.borderColor=[[UIColor orangeColor] CGColor];
        textField.layer.borderWidth= 1.0f;
    
        UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _leftIndent, 10)];
        [self setLeftViewMode:UITextFieldViewModeAlways];
        [self setLeftView:spacerView];
    
        return YES;
    }
    

    完成编辑后,我返回颜色:

    - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
        // Change border of text field that is edited to black
        textField.layer.masksToBounds=YES;
        textField.layer.borderColor=[[UIColor blackColor] CGColor];
        textField.layer.borderWidth= 1.0f;
    
        return YES;
    }
    

    在值更改时,我检查最大字符数:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
        // Restrict number of symbols in text field to "maxSymbols"
        NSUInteger oldLength = [textField.text length];
        NSUInteger replacementLength = [string length];
        NSUInteger rangeLength = range.length;
    
        NSUInteger newLength = oldLength - rangeLength + replacementLength;
    
        BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
    
        return newLength <= (int)_maxSymbols || returnKey;
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Community CDub    7 年前

    我不知道这是否是真正的答案,但我已经找到了下一个问题的答案 How properly subclass UITextField in iOS? (来自 justafinger ). 我不做任务 self.delegate = self; 在我的自定义控件中,但我有从视图控制器中的委托调用的方法。

    我希望这能帮助像我这样有问题的人。