Set the maximum character length of a UITextField

前端 未结 30 1704
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  遥遥无期
    2020-11-22 02:53

    The best way would be to set up a notification on the text changing. In your -awakeFromNib of your view controller method you'll want:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];
    

    Then in the same class add:

    - (void)limitTextField:(NSNotification *)note {
        int limit = 20;
        if ([[myTextField stringValue] length] > limit) {
            [myTextField setStringValue:[[myTextField stringValue] substringToIndex:limit]];
        }
    }
    

    Then link up the outlet myTextField to your UITextField and it will not let you add any more characters after you hit the limit. Be sure to add this to your dealloc method:

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:myTextField];
    

提交回复
热议问题