参考:http://www.jianshu.com/p/e5c6c9b455dd
=================tetfield使用集合===========
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LYBTextField : UITextField<UITextFieldDelegate>
//获取焦点的位置
-(NSRange)selectedRange;
//设置焦点的位置
-(void)setSelectedRange:(NSRange)range;
@end
NS_ASSUME_NONNULL_END
**********************
#import "LYBTextField.h"
@implementation LYBTextField
-(instancetype)initWithFrame:(CGRect)frame{
if(self=[super initWithFrame:frame]){
[self setTextfield];
}
return self;
}
//textField的相关设置
-(void)setTextfield{
//监听方法一:通过通知监听文本框变化
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(valueChange)name:UITextFieldTextDidChangeNotification object:self];
//监听方法二:
//[self addTarget:self action:@selector(valueChange)forControlEvents:UIControlEventEditingChanged];
self.placeholder=@"zhanweifu";
// self.backgroundColor=[UIColor greenColor];
//设置垂直的位置用contentVerticalAlignment
self.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
//设置水平的位置用textAlignment
//方法一:
self.textAlignment=NSTextAlignmentLeft;
//方法二:
// NSNumber * value = [NSNumber numberWithInteger:NSTextAlignmentRight];
// [self setValue:value forKeyPath:@"placeholderLabel.textAlignment"];
// //自定义键盘输入---会覆盖掉系统键盘
// UIView *audefineKeyBoard=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
// audefineKeyBoard.backgroundColor=[UIColor grayColor];
// self.inputView =audefineKeyBoard;
//设置文字自适应宽度
self.adjustsFontSizeToFitWidth = YES;
//设置自动缩小显示的最小字体大小,必须设置了adjustsFontSizeToFitWidth才生效
self.minimumFontSize = 13;
//首字母是否大写
self.autocapitalizationType = UITextAutocapitalizationTypeNone;
//键盘样式
self.keyboardType=UIKeyboardTypeDefault;
//清除按钮
self.clearButtonMode=UITextFieldViewModeAlways;
//右边的图片模式
self.rightViewMode=UITextFieldViewModeAlways;
// self.rightView=
//左边的图片模式
self.leftViewMode=UITextFieldViewModeWhileEditing;
// self.leftView=
self.delegate=self;
//边框样式
self.borderStyle=UITextBorderStyleRoundedRect;
//return键的显示样式
self.returnKeyType=UIReturnKeySearch;
/*键盘外观
typedef enum {
UIKeyboardAppearanceDefault, 默认外观,浅灰色
UIKeyboardAppearanceAlert, 深灰 石墨色
} UIReturnKeyType;
*/
self.keyboardAppearance=UIKeyboardAppearanceDefault;
// 1. TextView/TextField自定义光标的颜色
// //方法1:这种方法将影响所有TextField。
// [[UITextField appearance] setTintColor:[UIColor blackColor]];
//方法2
self.tintColor = [UIColor redColor];
//修改占位符文字大小
[self setValue:[UIFont systemFontOfSize:17]forKeyPath:@"placeholderLabel.font"];
//占位符文字颜色
// [self setValue:[UIColor orangeColor] forKeyPath:@"placeholderLabel.textColor"];
//设置是否使用密文输入
// self.secureTextEntry = YES;
//设置开始编辑时,清除已有的文字
// self.clearsOnBeginEditing = YES;
//设置背景图片
self.background = [UIImage imageNamed:@"one"];
//设置不可编辑时的背景图
self.disabledBackground = [UIImage imageNamed:@"two"];
}
//实现监听方法
- (void) valueChange
{ //判断文本框的内容
if (self.text.length >0 )
{
NSLog(@"文本框有内容");
}
}
//是否可以开始编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
//开始编辑
-(void)textFieldDidBeginEditing:(UITextField *)textField{
[self setSelectedRange:NSMakeRange(0, 5)];//开始编辑的时候选中前5个字符
[self selectedRange]; //光标选中的范围
}
//是否可以结束编辑
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
return YES;
}
//结束编辑、失去焦点
-(void)textFieldDidEndEditing:(UITextField *)textField{
}
//输入框内容该发生变化时,新输入的字符,,如果返回NO,文本宽高就不能编辑了。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"range变化---%ld--%ld",range.location,range.length);
NSLog(@"字符变化---%@",string);
return YES;
}
//开始编辑或者点击清除按钮
- (BOOL)textFieldShouldClear:(UITextField *)textField{
return YES;
}
//点击键盘右下角return按钮,回收键盘,取消编辑状态
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"点击了return按钮");
return YES;
}
// 结束编辑后文本的位置,缩进20
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset( bounds, 20, 0);
}
// 编辑的时候文本的位置,缩进10
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset( bounds, 10, 0);
}
返回placeholderLabel的bounds,改变返回值,是调整placeholderLabel的位置
//- (CGRect)placeholderRectForBounds:(CGRect)bounds {
//
// return CGRectMake(60, 0 ,self.bounds.size.width, self.bounds.size.height);
//}
// 这个函数是调整placeholder在placeholderLabel中绘制的位置以及范围,在里面可以设置字体和颜色
//- (void)drawPlaceholderInRect:(CGRect)rect {
// [super drawPlaceholderInRect:CGRectMake(0, -6 ,self.bounds.size.width, self.bounds.size.height)];
// [[self placeholder] drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor redColor]}];//设置placehold字体大小
//}
// TextView/TextField自定义光标长度或高度,可通过重写父类方法caretRectForPosition:实现
- (CGRect)caretRectForPosition:(UITextPosition *)position
{
CGRect originalRect = [super caretRectForPosition:position];
originalRect.size.height = self.font.lineHeight + 2;
originalRect.size.width = 5;
return originalRect;
}
控制清除按钮的位置
//
//-(CGRect)clearButtonRectForBounds:(CGRect)bounds
//{
// return CGRectMake(bounds.origin.x + bounds.size.width - 50, bounds.origin.y + bounds.size.height -20, 16, 16);
//}
//控制左视图位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds{
CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
return inset;
}
//获得光标选中的范围
-(NSRange)selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
NSLog(@"location---%ld---length---%ld",location,length);
return NSMakeRange(location, length);
}
//光标选中
-(void)setSelectedRange:(NSRange)range
{
UITextPosition* beginning = self.beginningOfDocument;//文本开始
UITextPosition* ending = self.endOfDocument;//文本结束
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];//光标起点
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];//光标终点
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];//选中的区间
[self setSelectedTextRange:selectionRange];//设置textfield光标选中
// [self setSelectedTextRange:[self textRangeFromPosition:beginning toPosition:ending]];//光标选中当前所有文本
}
@end
==============placeholed的设置========
我们有时需要定制化UITextField对象的风格,可以添加许多不同的重写方法,来改变文本字段的显示行为。这些方法都会返回一个CGRect结构,制定了文本字段每个部件的边界范围,甚至修改placeHolder颜色,字体。
– textRectForBounds: //重写来重置文字区域
– drawTextInRect: //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
– placeholderRectForBounds: //重写来重置占位符区域
– drawPlaceholderInRect: //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了
– borderRectForBounds: //重写来重置边缘区域
– editingRectForBounds: //重写来重置编辑区域
– clearButtonRectForBounds: //重写来重置clearButton位置,改变size可能导致button的图片失真
– leftViewRectForBounds:
– rightViewRectForBounds:
改变placehold的文字颜色
UITextField *phonetf=[[UITextField alloc]init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入您的手机号码" attributes:
@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFBBBBBB"], NSFontAttributeName:phonetf.font}];
phonetf.attributedPlaceholder = attrString;
[phoneview addSubview:phonetf];
//监听文本框变化,如果返回NO,文本宽高就不能编辑了。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// textfield 是输入或者删除字符之前的字符串;
NSLog(@"range-%@-****replace-%@",NSStringFromRange(range),string);
//range是光标选中的起始位置和选中的个数,string是输入的字符,输入哪个字符就显示哪个字符;
NSString * aString = [textField.text stringByReplacingCharactersInRange:range withString:string];//改变选中的字符
returnYES;
}
======设置点击textfield不弹出键盘======
[self.view endEditing:YES];
===================
- #pragma mark - 关于文本的设置
- -(void)textSetting
- {
- //找到文本输入框
- UITextField *textField = (id)[self.view viewWithTag:10];
- //设置文字
- // textField.text = @"我是文本框";
- //设置文字颜色
- textField.textColor = [UIColor redColor];
- //设置文字字体
- textField.font = [UIFont boldSystemFontOfSize:25];
- //设置文字对齐方式,默认居左
- textField.textAlignment = NSTextAlignmentRight;
- /**
- NSTextAlignmentLeft
- NSTextAlignmentRight
- NSTextAlignmentCenter
- */
- //设置文字自适应宽度
- textField.adjustsFontSizeToFitWidth = YES;
- //设置允许的最小字体,在adjustsFontSizeToFitWidth = YES,才有效
- textField.minimumFontSize = 17;
- //设置提示文字
- textField.placeholder = @"请输入用户名";
- //设置是否使用密文输入
- // textField.secureTextEntry = YES;
- //设置开始编辑时,清除已有的文字
- textField.clearsOnBeginEditing = YES;
- }
[objc] view plain copy print?
- #pragma mark - 关于样式的设置
- -(void)styleSetting
- {
- //找到已经创建好的UITextField
- UITextField *textField = (UITextField *)[self.view viewWithTag:10];
- //设置背景颜色
- // textField.backgroundColor = [UIColor cyanColor];
- //设置边框样式
- textField.borderStyle = UITextBorderStyleNone;
- /**
- UITextBorderStyleNone
- 无边框
- UITextBorderStyleLine
- 线性矩形
- UITextBorderStyleBezel
- 尖角矩形
- UITextBorderStyleRoundedRect
- 圆角矩形
- */
- //通过layer设置圆角
- textField.layer.cornerRadius = 10;
- textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
- textField.layer.borderWidth = 1;
- //设置是否显示清除按钮
- textField.clearButtonMode = UITextFieldViewModeUnlessEditing;
- //显示清除按钮的前提都是要有文字
- /**
- UITextFieldViewModeNever,
- //从不显示
- UITextFieldViewModeWhileEditing,
- //编辑时显示
- UITextFieldViewModeUnlessEditing,
- //非编辑时显示
- UITextFieldViewModeAlways
- //一直显示
- */
- //成为第一响应者
- //第一响应者,一个界面可能有多个可输入的控件,哪一个正在编辑哪一个就是第一响应者
- [textField becomeFirstResponder];
- //设置背景图片
- textField.background = [UIImage imageNamed:@"1.png"];
- //设置不可编辑时的背景图
- textField.disabledBackground = [UIImage imageNamed:@"5.png"];
- //设置是否可以编辑,YES 可以编辑,NO不可以
- // textField.enabled = NO;
- UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
- leftView.backgroundColor = [UIColor magentaColor];
- //设置左视图,所有直接或间接继承于UIView的类的对象,都可以作为左视图
- textField.leftView = leftView;
- //设置左视图的显示模式
- textField.leftViewMode = UITextFieldViewModeAlways;
- UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
- rightView.backgroundColor = [UIColor yellowColor];
- //设置右视图
- textField.rightView = rightView;
- //设置右视图的显示模式
- textField.rightViewMode = UITextFieldViewModeAlways;
- }
==============================================
=======================监听文本框的变化===================
//通知监听文本框
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
//添加按钮默认不可点击
self.addBtn.enabled =NO;
//通过通知监听文本框变化
[[NSNotificationCenterdefaultCenter]addObserver:self
selector:@selector(valueChange)name:UITextFieldTextDidChangeNotification
object:self.nameField];
[[NSNotificationCenterdefaultCenter]addObserver:self
selector:@selector(valueChange)name:UITextFieldTextDidChangeNotification
object:self.phoneField];
}
//实现监听方法
- (void) valueChange
{
//判断文本框的内容
if (self.nameField.text.length >0 &&self.phoneField.text.length >0)
{
self.addBtn.enabled =YES;
}
else
{
self.addBtn.enabled =NO;
}
}
//移除通知
- (void)dealloc
{
[[NSNotificationCenterdefaultCenter]removeObserver:self];
}
//监听文本框也可以用这个
在ViewDidLoad中调用[self setNoti];
-(void)setNoti{
[self.phonenumaddTarget:selfaction:@selector(textChange)forControlEvents:UIControlEventEditingChanged];
}
-(void)textChange{
NSLog(@"change");
}
========================textview
_inputTextView.autoresizingMask =UIViewAutoresizingFlexibleHeight;,在textview中输入文字,更具输入字符的多少,自动改变textview的大小。
=================退格变清空的问题==============================
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location > 0 && range.length == 1 && string.length == 0)
{
// Stores cursor position
UITextPosition *beginning = textField.beginningOfDocument;
UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
// Save the current text, in case iOS deletes the whole text
NSString *text = textField.text;
// Trigger deletion
[textField deleteBackward];
// iOS deleted the entire string
if (textField.text.length != text.length - 1)
{
textField.text = [text stringByReplacingCharactersInRange:range withString:string];
// Update cursor position
UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
[textField setSelectedTextRange:newSelectedRange];
}
return NO;
}
return YES;
}
===============仿照支付宝密码框的原理=========参考:http://www.jianshu.com/p/7059c017ad0a
看上去是6一个textfield,实际上只用了一个textfield;
创建一个UITextField,然后用5根竖线进行分割,这样就是让我们看到了一个有6个输入框;输入时的黑点点啊,是通过创建一个正方形的UIView,设置圆角为宽高的一半,就是一个圆了,具体如何在中间显示,就是定义这个黑色圆点的frame啊,让他显示在中间。
++++++++++++++++++++++++仿照支付宝密码框++++++++++++++++++=
#import <UIKit/UIKit.h>
@interface SYSafetySetUpController :UIViewController
@end
==============
#import "SYSafetySetUpController.h"
#define kDotSize CGSizeMake (10,10)//密码点的大小
#define kDotCount 6 //密码个数
#define K_Field_Height 45 //每一个输入框的高度
#define Screen_Width [UIScreen mainScreen].bounds.size.width
@interface SYSafetySetUpController ()<UITextFieldDelegate>
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)NSMutableArray *dotArray;//用于存放黑色的点点
@end
@implementation SYSafetySetUpController
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
[self.viewaddSubview:self.textField];
//页面出现时让键盘弹出
[self.textFieldbecomeFirstResponder];
[selfinitPwdTextField];
}
- (void)initPwdTextField
{
//每个密码输入框的宽度
CGFloat width = (Screen_Width - 32) /kDotCount;
//生成分割线
for (int i = 0; i <kDotCount - 1; i++) {
UIView *lineView = [[UIViewalloc]initWithFrame:CGRectMake(CGRectGetMinX(self.textField.frame) + (i + 1) * width, CGRectGetMinY(self.textField.frame), 1, K_Field_Height)];
lineView.backgroundColor = [UIColorgrayColor];
[self.viewaddSubview:lineView];
}
self.dotArray = [[NSMutableArrayalloc]init];
//生成中间的点
for (int i = 0; i <kDotCount; i++) {
UIView *dotView = [[UIViewalloc]initWithFrame:CGRectMake(CGRectGetMinX(self.textField.frame) + (width - kDotCount) / 2 + i * width,CGRectGetMinY(self.textField.frame) + (K_Field_Height -kDotSize.height) / 2,kDotSize.width,kDotSize.height)];
dotView.backgroundColor = [UIColorblackColor];
dotView.layer.cornerRadius =kDotSize.width / 2.0f;
dotView.clipsToBounds =YES;
dotView.hidden =YES;//先隐藏
[self.viewaddSubview:dotView];
//把创建的黑色点加入到数组中
[self.dotArrayaddObject:dotView];
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"变化%@", string);
if([stringisEqualToString:@"\n"]) {
//按回车关闭键盘
[textField resignFirstResponder];
returnNO;
} elseif(string.length == 0) {
//判断是不是删除键
returnYES;
}
else if(textField.text.length >=kDotCount) {
//输入的字符个数大于6,则无法继续输入,返回NO表示禁止输入
NSLog(@"输入的字符个数大于6,忽略输入");
returnNO;
} else {
returnYES;
}
}
/**
* 清除密码
*/
- (void)clearUpPassword
{
self.textField.text =@"";
[selftextFieldDidChange:self.textField];
}
/**
* 重置显示的点
*/
- (void)textFieldDidChange:(UITextField *)textField
{
NSLog(@"%@", textField.text);
for (UIView *dotViewinself.dotArray) {
dotView.hidden =YES;
}
for (int i = 0; i < textField.text.length; i++) {
((UIView *)[self.dotArrayobjectAtIndex:i]).hidden =NO;
}
if (textField.text.length ==kDotCount) {
NSLog(@"输入完毕");
//执行相关的操作,比如密码验证成功后,调用充值接口等;
}
}
#pragma mark - init
- (UITextField *)textField
{
if (!_textField) {
_textField = [[UITextFieldalloc]initWithFrame:CGRectMake(16, 100,Screen_Width - 32,K_Field_Height)];
_textField.backgroundColor = [UIColorwhiteColor];
//输入的文字颜色为白色
_textField.textColor = [UIColorwhiteColor];
//输入框光标的颜色为白色
_textField.tintColor = [UIColorwhiteColor];
_textField.delegate =self;
_textField.autocapitalizationType =UITextAutocapitalizationTypeNone;
_textField.keyboardType =UIKeyboardTypeNumberPad;
_textField.layer.borderColor = [[UIColorgrayColor]CGColor];
_textField.layer.borderWidth = 1;
[_textFieldaddTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
}
return_textField;
}
@end
===========实现自定义textfield或者textView=======================
#import <UIKit/UIKit.h>
//协议的内容
//@protocol UIKeyInput <UITextInputTraits>
//
//- (BOOL)hasText;
//- (void)insertText:(NSString *)text;
//- (void)deleteBackward;
//
//@end
@interface SIPTextView : UIView<UIKeyInput>
@property (nonatomic,retain)NSMutableString *textStore;
@property (nonatomic,retain)UIColor *textColor;
@property (nonatomic,retain)UIFont *font;
@end
========
#import "SIPTextView.h"
@implementation SIPTextView
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
self.backgroundColor = [UIColorwhiteColor];
self.textColor = [UIColorblackColor];
self.font = [UIFontboldSystemFontOfSize:12.0f];
self.textStore = [NSMutableStringstring];
self.layer.borderWidth=2;
self.layer.borderColor=[UIColorblackColor].CGColor;
}
returnself;
}
//协议中insertText方法会在用户在此控件有键盘输入时被调用,我们要在此记录输入的文本信息。
#pragma mark UIKeyInput protocol
-(void)insertText:(NSString *)text {
NSLog(@"有键盘输入了");
[self.textStoreappendString:text];//添加新输入的字符
//呼唤重绘
[selfsetNeedsDisplay];
}
//用于显示的文本对象是否有文本
- (BOOL)hasText
{
NSLog(@"shifou you文本");
// return self.textStore.length > 0;
returnNO;
}
//deleteBackward方法会在用户想按键删除一个输入字符时被调用,我们要在此删除一个字符:
- (void)deleteBackward
{
NSLog(@"删除");
if ([self.textStorelength] == 0) {
return;
}
NSRange theRange =NSMakeRange(self.textStore.length - 1, 1);
[self.textStoredeleteCharactersInRange:theRange];//删除字符串中的某个字符
//呼唤重绘
[selfsetNeedsDisplay];
}
//由于默认情况下控件无法成为第一响应者,所以必须更改此设置,并让其在被点击时成为第一响应者:
- (BOOL)canBecomeFirstResponder {
returnYES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (![selfisFirstResponder]) {
[selfbecomeFirstResponder];
}
}
//目前为止,此视图已经可以正常接收键盘输入消息了(可在insertText方法log出来看)。
//3.最后一步是把存储了键盘输入信息的文本属性显示出来,重写视图的drawRect方法如下:
- (CGRect)rectForTextWithInset:(CGFloat)inset {
returnCGRectInset(self.bounds, inset, inset);
}
- (void)drawRect:(CGRect)rect {
CGRect rectForText = [selfrectForTextWithInset:8.0f];
//设置当前绘制颜色
[self.textColorset];
//绘制矩形框边缘,UIRectFill(rect)则绘制矩形内部
//UIRectFrame(rect);
//一般用NSString的内置draw方法绘制文字---吧存储的字符串绘制到view上
[self.textStoredrawInRect:rectForTextwithAttributes:@{NSFontAttributeName:self.font}];
}
@end
******************************自定义密码框二:
#import "LYVeifycodeview.h"
@interface LYVeifycodeview()<UITextFieldDelegate>
@property(nonatomic,strong)NSMutableArray *squareArr;
@property(nonatomic,strong)NSMutableArray *dotArr;
@property(nonatomic,strong)UITextField *passwordTF;//验证码
@property(nonatomic,copy)NSString *pretxStr;//上一次tf的文本
@end
@implementation LYVeifycodeview
-(NSMutableArray *)squareArr{
if(nil==_squareArr){
_squareArr=[[NSMutableArray alloc]init];
}
return _squareArr;
}
-(NSMutableArray *)dotArr{
if(nil==_dotArr){
_dotArr=[[NSMutableArray alloc]init];
}
return _dotArr;
}
-(instancetype)initWithFrame:(CGRect)frame{
if(self==[super initWithFrame:frame]){
[self initviews];
}
return self;
}
-(void)initviews{
CGFloat w=30;
UIView *passwordview=[[UIView alloc]initWithFrame:CGRectMake(25, 100, WIDTH-50, 200)];
passwordview.backgroundColor=[UIColor whiteColor];
[self addSubview:passwordview];
UILabel *titlelbl=[[UILabel alloc]initWithFrame:CGRectMake(0, 10, passwordview.frame.size.width, 30)];
titlelbl.text=@"输入验证码";
titlelbl.textAlignment=NSTextAlignmentCenter;
[passwordview addSubview:titlelbl];
UITextField *passwordTF=[[UITextField alloc]initWithFrame:CGRectMake(w+10, 30+20,self.frame.size.width, 50)];
passwordTF.delegate=self;
passwordTF.tintColor =[UIColor clearColor];//光标颜色
passwordTF.textColor=[UIColor clearColor];
self.passwordTF=passwordTF;
passwordTF.borderStyle=UITextBorderStyleNone;
[passwordview addSubview:passwordTF];
//通过通知监听文本框变化
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(valueChange)name:UITextFieldTextDidChangeNotification object:self.passwordTF];
//在UITextfield上添加小方框
for (int i=0; i<6; i++) {
// 方框
UIView *square=[[UIView alloc]initWithFrame:CGRectMake(52*i, 0, 50, 50)];
square.borderColor=[UIColor colorWithHexString:@"#F5F8FA" alpha:1];
square.borderWidth=1;
[passwordTF addSubview:square];
[self.squareArr addObject:square];
//点
UIView *dot=[[UIView alloc]initWithFrame:CGRectMake(52*i+20, 20, 10, 10)];
dot.layer.cornerRadius=5;
dot.backgroundColor=[UIColor blackColor];
[passwordTF addSubview:dot];
[self.dotArr addObject:dot];
dot.alpha=0;
}
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
[passwordTF addGestureRecognizer:tap];
UIButton *cancelbtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 60+50, passwordview.frame.size.width/2, 50)];
[cancelbtn setTitle:@"取消" forState:UIControlStateNormal];
[cancelbtn setTitleColor:[UIColor colorWithHexString:@"#333333" alpha:1] forState:UIControlStateNormal];
[cancelbtn setBackgroundColor:[UIColor colorWithHexString:@"#F5F8FA" alpha:1]];
[cancelbtn addTarget:self action:@selector(cancelbtnclick:) forControlEvents:UIControlEventTouchUpInside];
[passwordview addSubview:cancelbtn];
UIButton *surebtn=[[UIButton alloc]initWithFrame:CGRectMake(passwordview.frame.size.width/2, 60+50, passwordview.frame.size.width/2,50)];
[surebtn setTitle:@"确定" forState:UIControlStateNormal];
[surebtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[surebtn setBackgroundColor:RGBA(21, 127, 230, 1.0)];
[surebtn setTitleColor:[UIColor colorWithWhite:0.8 alpha:0.8] forState:UIControlStateNormal];
[surebtn addTarget:self action:@selector(surebtnclick:) forControlEvents:UIControlEventTouchUpInside];
[passwordview addSubview:surebtn];
}
-(void)cancelbtnclick:(UIButton *)btn{
[self removeFromSuperview];
}
-(void)surebtnclick:(UIButton *)btn{
self.verycodeblock(self.passwordTF.text?self.passwordTF.text:@"");//
[self removeFromSuperview];
}
//
//实现监听方法
-(void)valueChange{
UIView *v=nil;
if(self.passwordTF.text.length<self.pretxStr.length){//删除
self.passwordTF.text=@"";
for (int i=0; i<6; i++) {
v = self.dotArr[i];
v.alpha=0;
}
}else{//输入
}
self.pretxStr=self.passwordTF.text;// 保存上一次的文本,用来判断是删除还是输入
//超过6个截取6个
if(self.passwordTF.text.length>6){
NSString *tx=[self.passwordTF.text substringWithRange:NSMakeRange(0, 6)];
self.passwordTF.text=tx;
}
//显示点的个数
for (int i=0; i<self.passwordTF.text.length; i++) {
v = self.dotArr[i];
v.alpha=1;
}
}
//手势
-(void)tap:(UITapGestureRecognizer *)tap{
[self.passwordTF becomeFirstResponder];
//更改光标的位置
[self cursorLocation:self.passwordTF index:self.passwordTF.text.length];
NSLog(@"手势出发");
}
// textField需要设置的textField,index要设置的光标位置
- (void)cursorLocation:(UITextField*)textField index:(NSInteger)index
{
NSRange range =NSMakeRange(index,0);
UITextPosition*start = [textField positionFromPosition:[textField beginningOfDocument]offset:range.location];
UITextPosition*end = [textField positionFromPosition:start offset:range.length];
[textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];
}
//监听框中的字符变化,也可以自定义UITextfield的键盘删除方法
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[self endEditing:YES];
return YES;
}
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
=============Textview中的return操作==============
//textview中的return操作
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车,即按下return
//在这里做你响应return键的代码
[self.tv resignFirstResponder];
return NO; //这里返回NO,就代表return键值失效,即页面上按下return,不会出现换行,如果为yes,则输入页面会换行
}
return YES;
}
==============textview设置文字居中=================
=====textfield文字居中=====
field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//===设置textView文字垂直居中======
- (void)contentSizeToFit
{
//先判断一下有没有文字(没文字就没必要设置居中了)
if([self.textView.text length]>0)
{
//textView的contentSize属性
CGSize contentSize = self.textView.contentSize;
//textView的内边距属性
UIEdgeInsets offset;
CGSize newSize = contentSize;
//如果文字内容高度没有超过textView的高度
if(contentSize.height <=self.textView.frame.size.height)
{
//textView的高度减去文字高度除以2就是Y方向的偏移量,也就是textView的上内边距
CGFloat offsetY = (self.textView.frame.size.height - contentSize.height)/2;
offset = UIEdgeInsetsMake(offsetY, 0, 0, 0);
}
else //如果文字高度超出textView的高度
{
newSize = self.textView.frame.size;
offset = UIEdgeInsetsZero;
CGFloat fontSize = 18;
//通过一个while循环,设置textView的文字大小,使内容不超过整个textView的高度(这个根据需要可以自己设置)
while (contentSize.height >self.textView.frame.size.height)
{
[self.textView setFont:[UIFont fontWithName:@"Helvetica Neue" size:fontSize--]];
contentSize = self.textView.contentSize;
}
newSize = contentSize;
}
//根据前面计算设置textView的ContentSize和Y方向偏移量
[self.textView setContentSize:newSize];
[self.textView setContentInset:offset];
}
}
=====
******UITextview回收键盘的方法
***********方法一1.如果你程序是有导航条的,可以在导航条上面加多一个Done的按钮,用来退出键盘,当然要先实UITextViewDelegate。
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *done = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(leaveEditMode)] autorelease];
self.navigationItem.rightBarButtonItem = done;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (void)leaveEditMode {
[self.textView resignFirstResponder];
}
************方法二
2.如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
**************方法三
-(void)addtoobar{
//键盘上添加toolbar
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView setBarStyle:UIBarStyleBlack];
UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneButton,nil];
[topView setItems:buttonsArray];
[tv setInputAccessoryView:topView];
}
-(void)dismissKeyBoard
{
[self.tv resignFirstResponder];
}