UITextView没有拿起文本输入iOS

时间:2015-08-06 12:51:37

标签: ios objective-c nsstring uitextview uialertview

我有UITextView,我想在空的时候显示警告

.h
@property (nonatomic, strong) IBOutlet UITextView *textField;

.m
- (IBAction)next:(id)sender {
if ([self.textField.text length] == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                                message:@"text empty"
                                                               delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
}
}

警告未显示,我可以继续前进,不输入任何文字。任何人都可以帮我找出原因吗?

感谢

3 个答案:

答案 0 :(得分:1)

textField有可能有空格字符。尝试使用以下内容修剪任何可能的空格:

NSString *text = [self.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet];
if ([text length] == 0) {
    ....
}

答案 1 :(得分:1)

试试这个 -

- (IBAction)next:(id)sender {

    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmed = [self.textField.text stringByTrimmingCharactersInSet:whitespace];
    if ([trimmed length] == 0) {
         // Text was empty or only whitespace.
         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                            message:@"text empty"
                                                           delegate:nil 
                                                  cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
        [alertView show];
   }
}

答案 2 :(得分:1)

I checked this from my end and its working perfectly.

Here is download link for testing the project

enter image description here

I am sure, textview is not connected to IB.

If its is connected to IB, then I would say to upload sample project on dropbox to check from our end.

相关问题