开发者

How to test a UITextField for being nil?

I am trying to make a part of my app where if the person doesn't change the blank text in my UITextField, then he/she can't go on to the next step. Basically, I want to test the UITextField for nil text. I have used the if (text == @"") method, but if the person clicks on the UITextField but doesn't type, then the if statement doesn't work. For some reason it doesn't think the text == nil or "". Am I implementing the code wrong. Any other options. Please hel开发者_如何学运维p!!!


You should be checking the length of the text property:

if([[textField text] length] == 0) {
  //do something...
}


Here's the category I use...

@implementation NSString (NSString+Extensions)            
- (BOOL)isNotBlank {
    return [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0;
}        
@end

This way a nil string would evaluate to false, which is correct. Creating an isBlank would return false for nil, which isn't correct.


I have write code to check the string is empty or not. This code also check for the string only space that is also empty for store name and address etc. this will help you.

NSString *stringTemp = textField.text;
stringTemp = [stringTemp stringByReplacingOccurrencesOfString:@" " withString:@""];

if ([stringTemp isEqualToString:@""]) {
    NSLog(@"Empty string");
}
else{
    NSLog(@"string has some content ");
}

Thanks


If I were you I would disable and enable the button while the user is typing. Imho it's better that the button looks disabled when there is no text than having the user click the button to tell him that he is not allowed to move to the next view. Most of apples own apps do it like this.

You achieve this behavior by using the UITextFieldDelegate method like this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // "Length of existing text" - "Length of replaced text" + "Length of replacement text"
    NSInteger textLength = [aTextView.text length] - range.length + [text length];

    if (textLength > 0) {
        doneButton.enabled = YES;
    }
    else {
        doneButton.enabled = NO;
    }
    return YES;
}

If you provide a prefilled textfield you have to enable the button in viewDidLoad (or where ever you want) and if you provide an empty field you have to disable it initally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜