文本字段的使用
文本字段是一个用户界面元素,通过应用程序来获取用户输入。
一个UITextfield如下所示:
重要的文本字段的属性
- 在没有任何用户输入时,显示占位符
- 正常文本
- 自动更正型
- 键盘类型
- 返回键类型
- 清除按钮模式
- 对齐方式
- 委托
更新xib中的属性
可以在Utility area(实用区域,窗口的右侧)更改xib在属性查看器中的文本字段属性。

文本字段委托
我们可以通过右击 UIElement 界面生成器中设置委托并将它连接到文件的所有者,如下所示:

使用委托的步骤:
- 1.设置委托如上图所示
- 2.添加委托到您的响应类
- 3.执行文本字段代表,重要的文本字段代表如下:
- (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
运行该应用程序会看到下面的输出

委托调用的方法基于用户操作。要知道调用委托时请参阅控制台输出。




点我分享笔记