【问题标题】:Create textfield and button programmatically click button get textfield text以编程方式创建文本字段和按钮单击按钮获取文本字段文本
【发布时间】:2014-12-25 11:17:35
【问题描述】:
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
}

【问题讨论】:

  • 使用标签是不错的选择。为两者分配标签,然后根据标签获取值。

标签: ios objective-c xcode


【解决方案1】:

按照以下方式将tag 发送给您的UITextField..

[textfiled setTag:101];

然后通过以下方式获取文本。

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

}

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      在您的 viewController.h 文件中分配

      UITextField *textField;
      

      在 ViewConroller.m 文件中这样做

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

      然后你可以通过

      获取文本值
      textField.text
      

      你也可以像@AbhishekSharma 那样做

      【讨论】:

      • 一次更正,你将使用它作为_textField或self.textField
      • 不可以直接使用。因为我没有设置 textField 的属性。所以可以直接使用,不用放_.@NickCatib
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      相关资源
      最近更新 更多