以编程方式添加textField并从另一种方法读取它?

时间:2013-08-02 15:55:38

标签: ios objective-c

在我的viewDidLoad中,我正在创建一个如下所示的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中的文本?

2 个答案:

答案 0 :(得分:3)

通过在界面中添加ivar来保持对UITextField对象的引用:

@interface MyViewController : UIViewController
{
UITextField *textField;
}

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

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

答案 1 :(得分:0)

您可以通过在界面中添加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全局化,以便可以从任何方法访问它。