委托textfield并限制它只输入数字

时间:2013-10-10 10:57:25

标签: ios objective-c delegates uitextfield

我正在以编程方式创建一些UITextField,当我尝试委托它们时,我会收到此警告:

  

NAVPlanViewController * const __strong'到不兼容类型id<UITextFieldDelegate>的参数

textHeight = [[UITextField alloc] initWithFrame:CGRectMake(0, 120, 160, 40)];
[textHeight setDelegate:self];

在我班级的.c我添加了@interface NAVPlanViewController : UIViewController <UITextViewDelegate>。 另外,我需要限制文本字段只接受数字,我想用这段代码来做,但是因为UITextField不会Delegate我无法检查它:

- (BOOL)textField:(UITextField *)textField 
        shouldChangeCharactersInRange:(NSRange)range 
                    replacementString:(NSString *)string {

    if (!string.length) {
            return YES;
    }

    if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] 
                                         invertedSet]].location != NSNotFound){
        //do something;
        return NO;
    }

2 个答案:

答案 0 :(得分:2)

NAVPlanViewController界面定义中,<UITextViewDelegate>应为<UITextFieldDelegate>

答案 1 :(得分:1)

@neilco是正确的符合

@interface YourViewController ()<UITextFieldDelegate>
{

}
@end

除了数字之外,将keyboardType设置为UIKeyboardTypeNumberPad,如

UITextField *age = [UITextField autolayoutView];
age.placeholder = kPlaceholderToEnterAge;
age.borderStyle = UITextBorderStyleRoundedRect;
age.clearButtonMode = UITextFieldViewModeWhileEditing;
age.returnKeyType = UIReturnKeyDefault;
age.keyboardType = UIKeyboardTypeNumberPad;
age.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
age.textAlignment = NSTextAlignmentCenter;