UITextField详解

#import "ViewController.h"

@interface ViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *attributeDict = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor redColor]};
    NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:@"默认富文本文字" attributes:attributeDict];

    // 初始化文本框 并 设置位置及大小
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 200, 40)];

    // 添加文本框
    [self.view addSubview:_textField];

    // 设置代理
    _textField.delegate = self;

    // 设置默认文字
    _textField.text = @"默认文字";

    // 设置文字字体和大小
    _textField.font = [UIFont fontWithName:@"Arial" size:18];

    // 设置文字颜色
    _textField.textColor = [UIColor blackColor];

    // 设置水印提示文字 (当输入框没有内容时显示的灰色文字)
    _textField.placeholder = @"请输入内容";

    // 设置默认富文本文字 和 水印提示富文本文字    会覆盖以前字体大小及颜色
    //_textField.attributedText = attributeString;
    //_textField.attributedPlaceholder = attributeString;

    // 设置文本框中文字属性
    //_textField.defaultTextAttributes = attributeDict;

    // 设置内容对齐方式
    _textField.textAlignment = NSTextAlignmentLeft;
    /*
     NSTextAlignmentLeft        左对齐 (默认)
     NSTextAlignmentCenter      居中对齐
     NSTextAlignmentRight       右对齐
     NSTextAlignmentJustified   Fully-justified. The last line in a paragraph is natural-aligned.
     NSTextAlignmentNatural     Indicates the default alignment for script
     */

    // 设置文本框再次编辑就清空内容 (默认NO)
    _textField.clearsOnBeginEditing = YES;

    // 设置密文输入 每输入一个字符就变成点 (默认NO)
    //_textField.secureTextEntry = YES;

    // 设置输入内容超出输入框时 字体自动缩小以适应文本窗口大小 (默认NO 字体保持原来大小 文本滚动)
    _textField.adjustsFontSizeToFitWidth = YES;

    // 设置文本框可以显示的最小字体 (最小是14)
    _textField.minimumFontSize = 14;

    // 设置键盘右下角的返回按钮是disabled(灰色不可点击) 当文本框中没有输入任何字符时 (默认NO)
    _textField.enablesReturnKeyAutomatically = YES;

    // 首字母是否大写
    _textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    /*
     UITextAutocapitalizationTypeNone               不自动大写 (默认)
     UITextAutocapitalizationTypeWords              单词首字母大写
     UITextAutocapitalizationTypeSentences          句子的首字母大写
     UITextAutocapitalizationTypeAllCharacters      所有字母都大写
     */

    // 设置清除按钮出现方式 文本框右边的小X
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    // 设置文本框左侧视图及出现方式
    _textField.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left.png"]];
    _textField.leftViewMode = UITextFieldViewModeAlways;
    // 设置文本框右侧视图及出现方式   与清除按钮冲突 需设置不同出现模式
    _textField.rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
    _textField.rightViewMode = UITextFieldViewModeUnlessEditing;
    /*
     UITextFieldViewModeNever           从不出现 (默认)
     UITextFieldViewModeWhileEditing    编辑时出现
     UITextFieldViewModeUnlessEditing   除了编辑外都出现
     UITextFieldViewModeAlways          总是可见
     */

    // 设置边框样式,只有设置了才会显示边框样式
      _textField.borderStyle = UITextBorderStyleNone;
    /*
     UITextBorderStyleNone          // 无边框 (默认)
     UITextBorderStyleLine          // 黑色直角边框
     UITextBorderStyleBezel         // 灰色直角边框 (带阴影)
     UITextBorderStyleRoundedRect   // 浅灰色圆角边框
     */

    // 设置输入框背景颜色
    _textField.backgroundColor = [UIColor brownColor];

    // 设置自定义背景图片 (图片被拉伸) (当UITextField的样式为UITextBorderStyleNone的时 才能修改此属性) 设置后边框会被忽略掉 颜色无效
    _textField.background = [UIImage imageNamed:@"background2.png"];

    // 设置当enable为no时 文本框背景图片
    //_textField.enabled = NO;
    //_textField.disabledBackground = [UIImage imageNamed:@"background1.png"];

    // 设置是否自动纠错
    _textField.autocorrectionType = UITextAutocorrectionTypeDefault;
    /*
     UITextAutocorrectionTypeDefault    自动纠错 默认
     UITextAutocorrectionTypeNo         不自动纠错
     UITextAutocorrectionTypeYes        自动纠错
     */

    // 设置弹出键盘样式
    _textField.keyboardType = UIKeyboardTypeDefault;
    /*
     UIKeyboardTypeDefault                  支持所有字符 (默认键盘)
     UIKeyboardTypeASCIICapable             支持ASCII的默认键盘
     UIKeyboardTypeNumbersAndPunctuation    标准电话键盘,支持+*#字符
     UIKeyboardTypeURL                      URL键盘,支持.com按钮 只支持URL字符
     UIKeyboardTypeNumberPad                数字键盘
     UIKeyboardTypePhonePad                 电话键盘
     UIKeyboardTypeNamePhonePad             电话键盘,也支持输入人名
     UIKeyboardTypeEmailAddress             用于输入电子 邮件地址的键盘
     UIKeyboardTypeDecimalPad               数字键盘 有数字和小数点
     UIKeyboardTypeTwitter                  优化的键盘,方便输入@、#字符
     */

    // 设置键盘return键样式
    _textField.returnKeyType = UIReturnKeySend;
    /*
     UIReturnKeyDefault         标有Return的灰色按钮 (默认)
     UIReturnKeyGo              标有Go的蓝色按钮
     UIReturnKeyGoogle          标有Google的蓝色按钮,用语搜索
     UIReturnKeyJoin            标有Join的蓝色按钮
     UIReturnKeyNext            标有Next的蓝色按钮
     UIReturnKeyRoute           标有Route的蓝色按钮
     UIReturnKeySearch          标有Search的蓝色按钮
     UIReturnKeySend            标有Send的蓝色按钮
     UIReturnKeyYahoo           标有Yahoo的蓝色按钮
     UIReturnKeyYahoo           标有Yahoo的蓝色按钮
     UIReturnKeyEmergencyCall   紧急呼叫按钮
     */

    // 设置键盘外观
    _textField.keyboardAppearance = UIKeyboardAppearanceDefault;
    /*
     UIKeyboardAppearanceDefault    浅灰色 (默认)
     UIKeyboardAppearanceAlert      深灰 石墨色
     */

    // 设置输入框成为第一响应时弹出的视图和辅助视图 (自定义键盘)
    //_textField.inputView = [UIView new];
    //_textField.inputAccessoryView = [UIView new];

    // 文本框是否正在编辑 readonly
    BOOL isEditing = _textField.isEditing;

    // 是否允许更改文本属性字典  默认NO
    _textField.allowsEditingTextAttributes = YES;
    // 当选择改变时自动重置文本属性
    _textField.typingAttributes = attributeDict;

    // 设置内容垂直、水平对齐方式    UITextField继承自UIControl,此类中有一个属性contentVerticalAlignment
    _textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField.contentHorizontalAlignment = UIControlContentVerticalAlignmentCenter;

    // 设置再次编辑时 原内容不消失 输入内容替代原内容 再次点击文本框可再原内容后接着输入 与clearsOnBeginEditing设置消失 此属性默认NO
    _textField.clearsOnInsertion = YES;

    // 结束编辑
    //[_textField endEditing:YES];

    // 注销第一响应 (收起键盘)
    [_textField resignFirstResponder];

    // 成为第一响应
    [_textField becomeFirstResponder];
}

#pragma mark - UITextFieldDelegate

// 设置是否可以进入编辑状态     设NO将无法修改 不出现键盘  YES可以修改 默认值
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    return YES;
}

// 当文本框成为 FirstResponder 时执行
- (void)textFieldDidBeginEditing:(UITextField *)textField {

    NSLog(@"BeginEditing");
}

// 设置是否可以结束编辑状态     设YES文本框将失去FirstResponder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {

    // 要想在用户结束编辑时阻止文本字段消失,可以返回NO 这对一些文本字段必须始终保持活跃状态的程序很有用,比如即时消息
    return YES;
}

// 当文本框失去 FirstResponder 时执行
- (void)textFieldDidEndEditing:(UITextField *)textField {

    NSLog(@"EndEditing");
}

// 文本框内容是否能被修改 每改变一次就会执行
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSLog(@"ChangeCharacters");
    // 可以跟踪字段内所做的最后一次修改,也可以对所有编辑做日志记录,用作审计用途。
    // NSRange 被改变文字的位置
    return YES;
}

// 设置是否允许 根据用户请求清除内容
- (BOOL)textFieldShouldClear:(UITextField *)textField {

    NSLog(@"Clear");
    // 可以设置在特定条件下才允许清除内容
    return YES;
}

// 当点击键盘的返回键(右下角)时执行
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSLog(@"Return");
    // 如果允许要调用resignFirstResponder方法 这会导致结束编辑 如果textFieldShouldEndEditing返回NO 键盘不能收起
    if (_textField == textField) {
        [_textField resignFirstResponder];
    }
    return YES;
}


#pragma mark - 通知

// UITextField派生自UIControl,所以UIControl类中的通知系统在文本字段中也可以使用。除了UIControl类的标准事件,你还可以使用下列UITextField类特有的事件
/*
 UITextFieldTextDidBeginEditingNotification
 UITextFieldTextDidChangeNotification
 UITextFieldTextDidEndEditingNotification

 当文本字段退出编辑模式时触发。通知的object属性存储了最终文本。

 因为文本字段要使用键盘输入文字,所以下面这些事件发生时,也会发送动作通知

 UIKeyboardWillShowNotification   // 键盘显示之前发送
 UIKeyboardDidShowNotification    // 键盘显示之后发送
 UIKeyboardWillHideNotification   // 键盘隐藏之前发送
 UIKeyboardDidHideNotification    // 键盘隐藏之后发送
 */

#pragma mark - 重写绘制

// 除了UITextField对象的风格选项,你还可以定制化UITextField对象,为他添加许多不同的重写方法,来改变文本字段的显示行为。这些方法都会返回一个CGRect结构,制定了文本字段每个部件的边界范围。以下方法都可以重写。
/*
 - (CGRect)borderRectForBounds:(CGRect)bounds;          // 重写来重置边缘区域
 - (CGRect)textRectForBounds:(CGRect)bounds;            // 重写来重置文字区域
 - (CGRect)placeholderRectForBounds:(CGRect)bounds;     // 重写来重置占位符区域
 - (CGRect)editingRectForBounds:(CGRect)bounds;         // 重写来重置编辑区域
 - (CGRect)clearButtonRectForBounds:(CGRect)bounds;     // 重写来重置clearButton位置,改变size可能导致button的图片失真
 - (CGRect)leftViewRectForBounds:(CGRect)bounds;        // 重写来重置leftView位置
 - (CGRect)rightViewRectForBounds:(CGRect)bounds;       // 重写来重置rightView位置

 - (void)drawTextInRect:(CGRect)rect;                   // 改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
 - (void)drawPlaceholderInRect:(CGRect)rect;            // 重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
 */
 @end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值