简体   繁体   中英

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

-(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.

Then, when you add textfield to the same as you did before.

In button click you can call that textbox via 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. I wouldn't recommend this.

give tag to your UITextField following way..

[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

UITextField *textField;

and in ViewConroller.m file do like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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