在 xcode 中以编程方式设置焦点并显示键盘?

在 xcode 中以编程方式设置焦点并显示键盘?

问题描述:

这是我的编码,即在单击 UIButton 时以编程方式创建 UITextField.但要增强的是,我想在创建 UITextField 时将焦点(并显示键盘)设置为新的 UITextField.

Here is my coding that UITextField is programmatically created when click on UIButton. But to enhancement is I want to set focus (and show keyboard) to new UITextField when UITextField is being created.

UITextField * txtComp=[[UITextField alloc]initWithFrame:CGRectMake(20,y, 450, 50)];
txtComp.borderStyle=UITextBorderStyleNone;
txtComp.delegate = self;
txtComp.tag=i+1;
txtComp.section=index;
txtComp.placeholder = @"New UITextField";
[txtComp becomeFirstResponder];

以上编码的工作是创建新的 UITextField,但即使设置了 becomeFirstResponder,也根本无法将焦点设置在新的 UITextField 上.

Above coding work as creating new UITextField but cannot be set focus on new UITextField at all even though becomeFirstResponder is set.

-(IBAction)buttonClicked:(id)sender

{

UITextField * txtComp=[[UITextField alloc]initWithFrame:CGRectMake(20,20, 450, 50)];
txtComp.borderStyle=UITextBorderStyleRoundedRect;
txtComp.delegate = self;


txtComp.placeholder = @"New UITextField";
[txtComp becomeFirstResponder];
[self.view addSubview:txtComp];
[self.view bringSubviewToFront:txtComp];

}