iOS 教程
文本字段是一個用戶界面元素,通過應用程序來獲取用戶輸入。
一個UITextfield如下所示:
重要的文本字段的屬性
可以在Utility area(實用區(qū)域,窗口的右側(cè))更改xib在屬性查看器中的文本字段屬性。
我們可以通過右擊?UIElement?界面生成器中設置委托并將它連接到文件的所有者,如下所示:
使用委托的步驟:
- (void)textFieldDidBeginEditing:(UITextField *)textField
- (void)textFieldDidEndEditing:(UITextField *)textField
以下我們使用簡單的實例來創(chuàng)建UI元素
ViewController 類將采用UITextFieldDelegate,修改ViewController.h文件,如下所示:
將方法addTextField添加到我們的 ViewController.m 文件
然后在 viewDidLoad 方法中調(diào)用此方法
在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
運行該應用程序會看到下面的輸出
委托調(diào)用的方法基于用戶操作。要知道調(diào)用委托時請參閱控制臺輸出。
其他擴展