[英]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.