2014-01-30 248 views
0

这是我的问题。我创建了一个UITextField。为什么我的UITextField委托方法不被调用?

.h文件中:

@property (strong, nonatomic) UITextField *emailTextField; 

.m文件:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.emailTextField.delegate=self; 
    [self setTextFields:120 :@" email" :self.emailTextField]; 
} 

-(void)setTextFields:(float)ycoord :(NSString *)text :(UITextField *)textField 
{ 
    CGRect frame = CGRectMake(60, ycoord, 180, 30); 
    textField = [[UITextField alloc]initWithFrame:frame]; 
    textField.backgroundColor = [UIColor whiteColor]; 
    textField.placeholder = text; 
    textField.font = [UIFont fontWithName:@"Baskerville" size:15]; 
    textField.allowsEditingTextAttributes=YES; 
    textField.autocorrectionType = UITextAutocorrectionTypeNo; 

    CALayer *lay = [textField layer]; 
    [lay setCornerRadius:5.0f]; 
    [self.view addSubview:textField]; 
} 

目的是保存用户放在文本字段中的文本。我尝试使用委托方法

-(void)textFieldDidEndEditing:(UITextField *)textField 

但该方法没有被调用(我把一个NSLog检查)。有人可以帮忙吗?

回答

5
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.emailTextField= [self setTextFields:120 :@" email"]; 
    self.emailTextField.delegate=self; 

    self.passwordTextField= [self setTextFields:200 :@" password"]; 
    self.passwordTextField.delegate=self; 

    self.nameTextField= [self setTextFields:250 :@" name"]; 
    self.nameTextField.delegate=self; 
} 

-(UITextField *)setTextFields:(float)ycoord :(NSString *)text{ 

    CGRect frame = CGRectMake(60, ycoord, 180, 30); 

    UITextField* textField = [[UITextField alloc]initWithFrame:frame]; 
    textField.backgroundColor = [UIColor whiteColor]; 
    textField.placeholder = text; 
    textField.font = [UIFont fontWithName:@"Baskerville" size:15]; 
    textField.allowsEditingTextAttributes=YES; 
    textField.autocorrectionType = UITextAutocorrectionTypeNo; 

    CALayer *lay = [textField layer]; 
    [lay setCornerRadius:5.0f]; 
    [self.view addSubview:textField]; 
    return textField; 
    } 
+0

我有其他的textField(self.passwordTextField和self.nameTextField)。这就是我使用函数的原因。所以我不能把你的代码放到我的代码中。 – Zoomzoom

+0

检查编辑的代码 – santhu

+0

它的工作!非常感谢!! – Zoomzoom

0
  1. 您设置emailTextField委托,但是当你创建的UITextField设置文本框。如果你将emailTextField合成为textField,这可以工作。

  2. 假设您正在执行emailTextFiled和textField之间的@synthesize,或者将emailTextField更改为textField,那么您在创建该对象之前设置了委托。你需要移动到设定的委托,直到你叫setTextFields后:

0

有几个问题:

你设定的委托,实际上创建了UITextField之前。

当您在setTextFields:方法中创建UITextField时,您永远不会将其分配给您的财产。您所做的只是将nil传入您的方法中,并且当您为方法中的变量赋值时,只会在该方法的上下文中分配它。它不会返回并设置属性。

0

可能是InterfaceBuilder构建视图的方式。

在应用程序启动时尝试[MyTextFieldDelegate new]。 当您的视图从NIB被唤醒时,您的课程将被注册并正确绑定到字段。

相关问题