简体   繁体   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];

I created textfield and button when i clicked button i want to get textfield text in buttonClicked function 我单击按钮时想创建文本框和按钮,但我想在buttonClicked函数中获取文本框的文本

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

Put the textfield declaration in the .h file and then access it without any problems. 将文本字段声明放在.h文件中,然后毫无问题地访问它。

Then, when you add textfield to the same as you did before. 然后,当您将文本字段添加到以前相同的位置时。

In button click you can call that textbox via self.textbox . 在按钮单击中,您可以通过self.textbox调用该文本框。

The other way to do this ( if you really want to keep this chunk of code ) would be to create UIView and then on click get superview of the button, go through elements in ui view and find UITextField. 这样做的另一种方法(如果您确实想保留这段代码)是创建UIView,然后单击获取按钮的超级视图,在ui视图中浏览元素并找到UITextField。 I wouldn't recommend this. 我不推荐这个。

give tag to your UITextField following way.. 通过以下方式给您的UITextField tag

[textfiled setTag:101];

then get text by following way. 然后按照以下方式获取文字。

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

}

in your viewController.h file assign 在您的viewController.h文件中分配

UITextField *textField;

and in ViewConroller.m file do like this 并在ViewConroller.m文件中这样做

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

Then you can get text value by 然后您可以通过

textField.text

also you can do as by @AbhishekSharma 你也可以像@AbhishekSharma那样

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

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