以编程方式添加textField,并在另一个方法中从中读取



在我的视图DidLoad中,我正在创建一个如下所示的textField:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10.0f,
                                                                       6.0f,
                                                                       toolBar.bounds.size.width - 20.0f - 68.0f,
                                                                       30.0f)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[toolBar addSubview:textField];

但我需要从IBAction方法的textField中读取文本。。

如何从该IBAction访问textField中的文本?

通过在接口中添加一个ivar来保持对UITextField对象的引用:

@interface MyViewController : UIViewController
{
UITextField *textField;
}

并在.m文件中添加您的方法:

- (IBAction)readTextField: (id)sender
{
NSLog(@"%@", textfield.text);
}

您可以通过在接口中添加ivar或创建textField的属性来保留对UITextField对象的引用。

@interface MyViewController : UIViewController
{
   UITextField *textField;
}

或创建属性

@property(nonatomic, retian) UITextField *textField;

并合成

@synthesize textField;
- (IBAction)GetTextFiledValue: (id)sender
  {
      NSLog(@"Your TextField value is : %@", [textfield text]);
  }

在这两种情况下,它都会起作用,但最重要的是使textField成为全局的,这样就可以从任何方法访问它。

最新更新