文本字段是一个用户界面元素,通过应用程序来获取用户输入。
一个UITextfield如下所示:
重要的文本字段的属性
可以在Utility area(实用区域,窗口的右侧)更改xib在属性查看器中的文本字段属性。
我们可以通过右击 UIElement 界面生成器中设置委托并将它连接到文件的所有者,如下所示:
使用委托的步骤:
- (void)textFieldDidBeginEditing:(UITextField *)textField
- (void)textFieldDidEndEditing:(UITextField *)textField
以下我们使用简单的实例来创建UI元素
ViewController 类将采用UITextFieldDelegate,修改ViewController.h文件,如下所示:
将方法addTextField添加到我们的 ViewController.m 文件
然后在 viewDidLoad 方法中调用此方法
在ViewController.m中更新viewDidLoad,如下所示
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //The custom method to create our textfield is called [self addTextField]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)addTextField{ // This allocates a label UILabel *prefixLabel = [[UILabel alloc]initWithFrame:CGRectZero]; //This sets the label text prefixLabel.text =@"## "; // This sets the font for the label [prefixLabel setFont:[UIFont boldSystemFontOfSize:14]]; // This fits the frame to size of the text [prefixLabel sizeToFit]; // This allocates the textfield and sets its frame UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(20, 50, 280, 30)]; // This sets the border style of the text field textField.borderStyle = UITextBorderStyleRoundedRect; textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; [textField setFont:[UIFont boldSystemFontOfSize:12]]; //Placeholder text is displayed when no text is typed textField.placeholder = @"Simple Text field"; //Prefix label is set as left view and the text starts after that textField.leftView = prefixLabel; //It set when the left prefixLabel to be displayed textField.leftViewMode = UITextFieldViewModeAlways; // Adds the textField to the view. [self.view addSubview:textField]; // sets the delegate to the current class textField.delegate = self; } // pragma mark is used for easy access of code in Xcode #pragma mark - TextField Delegates // This method is called once we click inside the textField -(void)textFieldDidBeginEditing:(UITextField *)textField{ NSLog(@"Text field did begin editing"); } // This method is called once we complete editing -(void)textFieldDidEndEditing:(UITextField *)textField{ NSLog(@"Text field ended editing"); } // This method enables or disables the processing of return key -(BOOL) textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; } - (void)viewDidUnload { label = nil; [super viewDidUnload]; } @end
运行该应用程序会看到下面的输出
委托调用的方法基于用户操作。要知道调用委托时请参阅控制台输出。