2015-12-22 59 views
0

我想防止保存数据并在任何文本字段为空时显示警报。这就是我所拥有的,当我点击保存按钮时,弹出警报,但是文本框在空白时仍然保留空白文本。检查UITextfield是否为空并显示警报

// check if text feild is empty 

    if usernameLabel.text == "" || passwordLabel.text == "" || phoneNumber.text == "" || service.text == "" || address.text == "" { 

     // Alert 
     let optionMenu = UIAlertController(title: nil, message: "Please Enter Text", preferredStyle: .Alert) 

     // Add actions to the menu 
     let cancelAction = UIAlertAction(title: "Ok", style: .Cancel, handler: 
      nil) 
     optionMenu.addAction(cancelAction) 

     // Display the menu 
     self.presentViewController(optionMenu, animated: true, completion: nil) 

    } 


} //End save button 
+0

你写的,如果(usernameLabel .hasText()|| passwordLabel .hasText()){ } –

+1

是攒动写在别的这种情况的? –

+0

偏离主题,但我不会将“UITextField”实例命名为“用户名**标签**”或“密码**标签**”;如果只是为了避免混淆... –

回答

1

回报,你首先先卸下whitspace,因为它也考虑为字符。所以必须删除空格使用下面的代码,

-(NSString *)remove_whitespace:(NSString *)string_data /* Remove whitspace in the string */ 
{ 
     NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; 
     string_data = [string_data stringByTrimmingCharactersInSet:whitespace]; 
     return string_data; 
} 

然后,计算字符串的长度。如果它大于0继续,否则弹出如下的错误,

if([self remove_whitespace:textstring]) 
{ 
NSLog(@"work"); 
    } 
else 
{ 
NSLog(@"so error"); 
} 

明白了吗?

1

您若结束后添加这样

if usernameLabel.text.length == 0 || passwordLabel.text.length == 0 || phoneNumber.text.length == 0 || service.text.length == 0 || address.text.length == 0 { 

    // your code 
    return 
} 
+0

我试过这个,但得到相同的结果。它不会停止保存空白文本 –

+0

更新的答案。这将做 – vaibby

1
if(usernameLabel.text.characters.count == 0 || passwordLabel.text.characters.count == 0 || phoneNumber.text.characters.count == 0 || service.text.characters.count == 0 || address.text.characters.count == 0) 
{ 
    // your code 
    return 
} 

使用.characters.count来检查是否检查textfield是否为空。

+0

我试过这个,我得到一个错误,.length不是字符串的类型 –

+0

我已经更新了我的答案...请检查它 –