示例代码和步骤
Step 1 − 我们将使用为 UI 元素创建的示例应用程序。
Step 2 − 我们的 ViewController 类将采用 UITextFieldDelegate 和我们的 ViewController.h 文件更新如下 -
#import <UIKit/UIKit.h>
// You can notice the adddition of UITextFieldDelegate below
@interface ViewController : UIViewController<UITextFieldDelegate>
@end
Step 3 - 然后我们添加一个方法 addTextField 到我们的 ViewController.m 文件。
Step 4 - 然后我们在 viewDidLoad 方法中调用这个方法。
Step 5 − 更新 viewDidLoad 在 ViewController.m 如下 -
#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.contentVerticalMoognment = UIControlContentVerticalMoognmentCenter;
[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
Step 6 - 当我们运行应用程序时,我们将得到以下输出。
Step 7− 基于用户操作调用委托方法。查看控制台输出以了解何时调用委托。