繁体   English   中英

创建文本字段和按钮以编程方式单击按钮获取文本字段文本

[英]Create textfield and button programmatically click button get textfield text

CGRect frame = CGRectMake(40, 40, 200, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:frame];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.textColor = [UIColor blackColor];
textField.font = [UIFont systemFontOfSize:17.0];
textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeYes;
textField.keyboardType = UIKeyboardTypeDefault;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[but setFrame:CGRectMake(80, 80, 215, 40)];
[but setTitle:@"Login" forState:UIControlStateNormal];
[but setExclusiveTouch:YES];

[view addSubview:but];
[view addSubview:textField];
[view addSubview:label];

我单击按钮时想创建文本框和按钮,但我想在buttonClicked函数中获取文本框的文本

-(void) buttonClicked:(UIButton*)sender
{
    // I want to get textfield text right here
}

将文本字段声明放在.h文件中,然后毫无问题地访问它。

然后,当您将文本字段添加到以前相同的位置时。

在按钮单击中,您可以通过self.textbox调用该文本框。

这样做的另一种方法(如果您确实想保留这段代码)是创建UIView,然后单击获取按钮的超级视图,在ui视图中浏览元素并找到UITextField。 我不推荐这个。

通过以下方式给您的UITextField tag

[textfiled setTag:101];

然后按照以下方式获取文字。

-(void) buttonClicked:(UIButton*)sender
{
    UITextField * textField = (UITextField *)[self.view viewWithTag:101];
    NSLog(@"your text = %@",textField.text);

}

在您的viewController.h文件中分配

UITextField *textField;

并在ViewConroller.m文件中这样做

CGRect frame = CGRectMake(40, 40, 200, 30);
textField = [[UITextField alloc] initWithFrame:frame];
...

然后您可以通过

textField.text

你也可以像@AbhishekSharma那样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM