基础创建
// 创建组件
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 330, 80)];
// 添加视图
[self.view addSubview: textField];
// 外框类型
[textField setBorderStyle:UITextBorderStyleRoundedRect];
// 占位符
textField.placeholder = @"password";
// 光标颜色
textField.tintColor = [UIColor redColor];
// 安全显示
// textField.secureTextEntry = YES;
// 自动纠正
textField.autocorrectionType = UITextAutocorrectionTypeNo;
// 字体大小
textField.font = [UIFont systemFontOfSize:72];
// 编辑时显示删除按钮
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
// 键盘显示类型
textField.keyboardType = UIKeyboardTypeDefault;
// 键盘返回类型
textField.returnKeyType = UIReturnKeyDone;
// 键盘外观
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
// 设置居中输入
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
// 自适应高度(自己设置的高度无效)
textField.autoresizingMask = UIViewAutoresizingFlexibleHeight;
// 左/右视图,唯一有效的就是宽度
textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 100)];
// 显示模式
textField.leftViewMode = UITextFieldViewModeAlways;
// 设置代理
textField.delegate = self;
// 设置弹出视图,不弹出键盘,仅高度有效
// textField.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 100)];
// 当改变字体大小适应宽
textField.adjustsFontSizeToFitWidth = YES;
// 适应宽度时支持的最小字号
textField.minimumFontSize = 5;
// 再次编辑时是否清空
textField.clearsOnBeginEditing = NO;
// 貌似点击回去再次编辑时不清楚,但是只要一输入内容就会清除之前的
textField.clearsOnInsertion = NO;
// 设置return样式,除了默认外,其他的按钮都是蓝颜色背景
textField.returnKeyType = UIReturnKeyGo;
改变占位字符属性
- 方式一: 富文本
NSMutableAttributedString *pswd = [[NSMutableAttributedString alloc] initWithString:@"pswd"];
[pswd setAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} range:NSMakeRange(0, 2)];
[pswd setAttributes:@{NSForegroundColorAttributeName : [UIColor yellowColor], NSFontAttributeName : [UIFont systemFontOfSize:30]} range:NSMakeRange(2, 2)];
textField.attributedPlaceholder = pswd;
- 方式二: 重绘
- (void)drawPlaceholderInRect:(CGRect)rect {
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
attributes[NSFontAttributeName] = [UIFont systemFontOfSize:12];
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
- 方式三: KVC
// 设置占位文字后
textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
继承UItextField
DDYTextField.h
#import <UIKit/UIKit.h>
@interface DDYTextField : UITextField
@end
DDYTextField.m
#import "DDYTextField.h"
@implementation DDYTextField
#pragma mark 控制清除按钮的位置
- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x+ bounds.size.width-50, bounds.origin.y+ bounds.size.height-20,16,16);
}
#pragma mark 控制placeHolder的位置,左右缩20
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
//return CGRectInset(bounds, 10, 0);
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y+16, bounds.size.width -10, bounds.size.height);
return inset;
}
#pragma mark 控制显示文本的位置
- (CGRect)textRectForBounds:(CGRect)bounds {
//return CGRectInset(bounds, 50, 0);
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
return inset;
}
#pragma mark 控制编辑文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds {
//return CGRectInset( bounds, 10 , 0 );
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
return inset;
}
#pragma mark 控制placeHolder的颜色、字体
- (void)drawPlaceholderInRect:(CGRect)rect {
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
attributes[NSFontAttributeName] = [UIFont systemFontOfSize:12];
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
#pragma mark 禁止复制,粘贴,全选菜单
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
// 禁用粘贴功能
if (action == @selector(paste:))
return NO;
// 禁用选择功能
if (action == @selector(select:))
return NO;
// 禁用全选功能
if (action == @selector(selectAll:))
return NO;
return [super canPerformAction:action withSender:sender];
}
@end
禁止输入框所有功能按钮
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
UIMenuController *menuController = [UIMenuController sharedMenuController];
if (menuController) {
[UIMenuController sharedMenuController].menuVisible = NO;
}
return NO;
}
文本框变化监听
1 代理方式
// <UITextFieldDelegate>
- (void)viewDidLoad {
textField.delegate = self; //添加代理
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 如果NO就不会显示
return true;
}
2 通知方式
- (void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
//addObserver:self 监听者对象
//name 监听的改变对象的方法
//object 监听的对象 nil 全部监听
}
- (void)textChange {
NSLog(@"%@", textField.text);
}
/** 记得移除 */
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self]; //移除监听
}
动态添加执行方法
- (void) viewDidLoad {
[_userName addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
//forControlEvents 触发事件
}
- (void)textChange {
NSLog(@"%@", _userName.text);
}
纯数字问题
当要求输入手机号或者数字密码时,要禁止键盘输入其他字符,甚至防止粘贴方式输入特殊字符
网上很多这种方式
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return [self isPureInt:string];
}
- (BOOL)isPureInt:(NSString*)string {
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
不足显而易见,当返回NO,就没法编辑、删除。
我的一种实现方式
_phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
[_phoneTextField addTarget:self action:@selector(textFieldTextChange) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldTextChange {
if (_phoneTextField.text.length>10) {
_phoneTextField.text = [_phoneTextField.text substringToIndex:11];
} else if (_phoneTextField.text.length > 0) {
_phoneTextField.text = [[_phoneTextField.text componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];
}
}