UI控件11 UITextField 代码实战+解析

1.在Deployment Info中调整开发环境到9.0 以便大多数客户都能够使用
ViewController.h文件声明:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    //定义一个 TextFiled 文本输入区域
    //例如 用户名,密码,等需要输入文本文字的内容区
    //特点是 只能输入 显示 单行文本
    UITextField * _textFiled;
}

//定义属性
@property(retain, nonatomic) UITextField * textField;

@end

ViewController.m文件实现:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

//同步定义属性
@synthesize textField = _textFiled;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //创建一个文本输入区对象
    self.textField = [[UITextField alloc]init];
    
    //设定文本输入区的位置大小
    self.textField.frame = CGRectMake(100, 100, 100, 40);
    
    //设置textField的内容文字
    self.textField.text = @"用户名";
    
    //设置文字的字体大小
    self.textField.font = [UIFont systemFontOfSize:15];
    
    //设置字体的颜色
    self.textField.textColor = [UIColor blackColor];
    
    //设置文本区域的风格
    //UITextBorderStyleRoundedRect : 圆角风格
    //UITextBorderStyleLine: 线条风格
    //UITextBorderStyleBezel : Bexel线框
    //UITextBorderStyleNone : 无边框风格
    self.textField.borderStyle = UITextBorderStyleBezel;
    
    //设置虚拟键盘风格
    //UIKeyboardTypeDefault : 默认风格
    //UIKeyboardTypeNamePhonePad: 字母和数字组合风格
    //UIKeyboardTypeNumberPad : 纯数字风格
    self.textField.keyboardType = UIKeyboardTypeNumberPad;
    
    //提示文字信息
    //当text属性为空时,显示此条信息 浅灰色提示字
    self.textField.placeholder = @"请输入用户名";
    
    //是否作为密码输入
    self.textField.secureTextEntry = NO;
    
    [self.view addSubview:self.textField];
    
    //设置代理对象
    self.textField.delegate = self;
}

//是否可以进行输入
//如果返回YES 可以进行输入  其实默认情况下就是YES 所以也可以不用写这个函数
//什么时候返回 NO ? 当你的权限不够时 比如没有注册用户 就不能发帖子
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

//是否可以结束输入
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"开始编辑");
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"结束编辑");
}

//点击屏幕空白处调用此函数
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //使虚拟键盘回收 不再作为第一消息响应者
    [self.textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

猜你喜欢

转载自blog.csdn.net/teropk/article/details/81227024
今日推荐