【问题标题】:UITextFeld Comparison FailingUITextFeld 比较失败
【发布时间】:2012-01-11 00:03:48
【问题描述】:

我有一个 UITextField,我像这样创建它:

firstnameField1 = [[UITextField alloc] initWithFrame:CGRectMake(85+320*4, 80, 150, 30)];
    [firstnameField1 setBorderStyle:UITextBorderStyleRoundedRect];
    [firstnameField1 setPlaceholder:@"Firstname"];
    [firstnameField1 setDelegate:self];
    [firstnameField1 setReturnKeyType:UIReturnKeyNext];
    [scrollViewController addSubview:firstnameField1];

当用户点击返回键时,我想检查文本字段是否输入了任何内容,如果它为空,则用户没有输入任何内容,我想返回并显示一个标签,告诉用户该字段是必须先填写,然后才能继续,就像您在各处看到的一样。

我做以下检查:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //Check if the user has typed anything
    if (textField.text == @"") {
        //If not, show 'required' labels
        [firstNameRequiredLbl1 setAlpha:1];
        [surnameRequiredLbl1 setAlpha:1];
        [firstNameRequiredLbl2 setAlpha:1];
        [surnameRequiredLbl2 setAlpha:1];
        return YES;
    }

    //Do all my other stuff, cut out for ease of reading, 100% doesn't affect this anyway

    return YES;
}

我在最后一个方法上设置了一个断点,无论我是否在该文本字段中输入,它都会跳过该 if 语句。

有什么想法吗?谢谢。

【问题讨论】:

    标签: iphone objective-c ipad uitextfield


    【解决方案1】:

    你会想要改变 textField.text == @""

    至:textField.text.length == 0textField.text isEqualToString:@""

    在这种情况下,== 运算符实际上在做的是检查字符串是否存储在同一内存区域中,而不是它们是否包含相同的字符。

    【讨论】:

      【解决方案2】:

      您无法以这种方式比较 NSString 文本字符串。改用这个:

      if ([textField.text isEqualToString: @""])
      

      【讨论】:

        猜你喜欢
        • 2017-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-04
        • 2011-07-09
        • 1970-01-01
        • 2018-07-21
        相关资源
        最近更新 更多