chenzhao

  • java
  • iOS
  • IT
知识积累
不积跬步无以至千里
  1. 首页
  2. iOS
  3. 正文

UITextField 属性

2016年 8月 26日 90点热度 0人点赞 0条评论
titleTextField.becomeFirstResponder()  设置为第一响应者
/初始化textfield并设置位置及大小

  UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)];


//设置边框样式,只有设置了才会显示边框样式

  text.borderStyle = UITextBorderStyleRoundedRect;

  typedef enum {

    UITextBorderStyleNone,

    UITextBorderStyleLine,

    UITextBorderStyleBezel,

    UITextBorderStyleRoundedRect

  } UITextBorderStyle;


//设置输入框的背景颜色,此时设置为白色 如果使用了自定义的背景图片边框会被忽略掉


   text.backgroundColor = [UIColor whiteColor];


//设置背景

  text.background = [UIImage imageNamed:@"dd.png"];


//设置背景

  text.disabledBackground = [UIImage imageNamed:@"cc.png"];

//当输入框没有内容时,水印提示 提示内容为password

  text.placeholder = @"password";


//设置输入框内容的字体样式和大小

  text.font = [UIFont fontWithName:@"Arial" size:20.0f];


//设置字体颜色

  text.textColor = [UIColor redColor];


//输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容

  text.clearButtonMode = UITextFieldViewModeAlways;


typedef enum {

    UITextFieldViewModeNever,  重不出现

    UITextFieldViewModeWhileEditing, 编辑时出现

    UITextFieldViewModeUnlessEditing,  除了编辑外都出现

    UITextFieldViewModeAlways   一直出现

} UITextFieldViewMode;


//输入框中一开始就有的文字

  text.text = @"一开始就在输入框的文字";


//每输入一个字符就变成点 用语密码输入

  text.secureTextEntry = YES;


//是否纠错

  text.autocorrectionType = UITextAutocorrectionTypeNo;


typedef enum {

    UITextAutocorrectionTypeDefault, 默认

    UITextAutocorrectionTypeNo,   不自动纠错

    UITextAutocorrectionTypeYes,  自动纠错

} UITextAutocorrectionType;


//再次编辑就清空

  text.clearsOnBeginEditing = YES;


//内容对齐方式

  text.textAlignment = UITextAlignmentLeft;


//内容的垂直对齐方式  UITextField继承自UIControl,此类中有一个属性contentVerticalAlignment

  text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;


//设置为YES时文本会自动缩小以适应文本窗口大小.默认是保持原来大小,而让长文本滚动


  textFied.adjustsFontSizeToFitWidth = YES;


//设置自动缩小显示的最小字体大小

  text.minimumFontSize = 20;


//设置键盘的样式

  text.keyboardType = UIKeyboardTypeNumberPad;


typedef enum {

    UIKeyboardTypeDefault,       默认键盘,支持所有字符

    UIKeyboardTypeASCIICapable,  支持ASCII的默认键盘

    UIKeyboardTypeNumbersAndPunctuation,  标准电话键盘,支持+*#字符

    UIKeyboardTypeURL,            URL键盘,支持.com按钮 只支持URL字符

UIKeyboardTypeNumberPad,              数字键盘

UIKeyboardTypePhonePad,     电话键盘

    UIKeyboardTypeNamePhonePad,   电话键盘,也支持输入人名

UIKeyboardTypeEmailAddress,   用于输入电子 邮件地址的键盘

UIKeyboardTypeDecimalPad,     数字键盘 有数字和小数点

    UIKeyboardTypeTwitter,        优化的键盘,方便输入@、#字符

    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable,

} UIKeyboardType;


//首字母是否大写

  text.autocapitalizationType = UITextAutocapitalizationTypeNone;


typedef enum {

    UITextAutocapitalizationTypeNone, 不自动大写

    UITextAutocapitalizationTypeWords,  单词首字母大写

    UITextAutocapitalizationTypeSentences,  句子的首字母大写

    UITextAutocapitalizationTypeAllCharacters, 所有字母都大写

} UITextAutocapitalizationType;


//return键变成什么键

  text.returnKeyType =UIReturnKeyDone;


typedef enum {

    UIReturnKeyDefault, 默认 灰色按钮,标有Return

    UIReturnKeyGo,      标有Go的蓝色按钮

    UIReturnKeyGoogle,标有Google的蓝色按钮,用语搜索

    UIReturnKeyJoin,标有Join的蓝色按钮

    UIReturnKeyNext,标有Next的蓝色按钮

    UIReturnKeyRoute,标有Route的蓝色按钮

    UIReturnKeySearch,标有Search的蓝色按钮

    UIReturnKeySend,标有Send的蓝色按钮

    UIReturnKeyYahoo,标有Yahoo的蓝色按钮

    UIReturnKeyYahoo,标有Yahoo的蓝色按钮

    UIReturnKeyEmergencyCall, 紧急呼叫按钮

} UIReturnKeyType;


//键盘外观

textView.keyboardAppearance=UIKeyboardAppearanceDefault;

typedef enum {

UIKeyboardAppearanceDefault, 默认外观,浅灰色

UIKeyboardAppearanceAlert,     深灰 石墨色


} UIReturnKeyType;



//设置代理 用于实现协议

  text.delegate = self;


//把textfield加到视图中

  [self.window addSubview:text];


//最右侧加图片是以下代码   左侧类似

    UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];

    text.rightView=image;

    text.rightViewMode = UITextFieldViewModeAlways;


typedef enum {

    UITextFieldViewModeNever,

    UITextFieldViewModeWhileEditing,

    UITextFieldViewModeUnlessEditing,

    UITextFieldViewModeAlways

} UITextFieldViewMode;



//按return键键盘往下收  becomeFirstResponder


类要采用UITextFieldDelegate协议


text.delegate = self;  声明text的代理是我,我会去实现把键盘往下收的方法 这个方法在UITextFieldDelegate里所以我们要采用UITextFieldDelegate这个协议


- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [text resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收

    return YES;

}



重写绘制行为

除了UITextField对象的风格选项,你还可以定制化UITextField对象,为他添加许多不同的重写方法,来改变文本字段的显示行为。这些方法都会返回一个CGRect结构,制定了文本字段每个部件的边界范围。以下方法都可以重写。


– textRectForBounds:      //重写来重置文字区域

– drawTextInRect:          //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.

– placeholderRectForBounds:  //重写来重置占位符区域

– drawPlaceholderInRect:  //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.

– borderRectForBounds:  //重写来重置边缘区域

– editingRectForBounds:  //重写来重置编辑区域

– clearButtonRectForBounds:  //重写来重置clearButton位置,改变size可能导致button的图片失真

– leftViewRectForBounds:

– rightViewRectForBounds:


委托方法


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{


//返回一个BOOL值,指定是否循序文本字段开始编辑



    return YES;

}


- (void)textFieldDidBeginEditing:(UITextField *)textField{

 //开始编辑时触发,文本字段将成为first responder

}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{

//返回BOOL值,指定是否允许文本字段结束编辑,当编辑结束,文本字段会让出first responder

   //要想在用户结束编辑时阻止文本字段消失,可以返回NO

   //这对一些文本字段必须始终保持活跃状态的程序很有用,比如即时消息


    return NO;

}


- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

//当用户使用自动更正功能,把输入的文字修改为推荐的文字时,就会调用这个方法。

//这对于想要加入撤销选项的应用程序特别有用

//可以跟踪字段内所做的最后一次修改,也可以对所有编辑做日志记录,用作审计用途。

//要防止文字被改变可以返回NO

//这个方法的参数中有一个NSRange对象,指明了被改变文字的位置,建议修改的文本也在其中



     return YES;

}


- (BOOL)textFieldShouldClear:(UITextField *)textField{


//返回一个BOOL值指明是否允许根据用户请求清除内容

//可以设置在特定条件下才允许清除内容


     return YES;

}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{


//返回一个BOOL值,指明是否允许在按下回车键时结束编辑

 //如果允许要调用resignFirstResponder 方法,这回导致结束编辑,而键盘会被收起[textField resignFirstResponder];

//查一下resign这个单词的意思就明白这个方法了

     return YES;

}




通知

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


UITextFieldTextDidBeginEditingNotification

UITextFieldTextDidChangeNotification

UITextFieldTextDidEndEditingNotification

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


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


UIKeyboardWillShowNotification   //键盘显示之前发送

UIKeyboardDidShowNotification    //键盘显示之后发送

UIKeyboardWillHideNotification   //键盘隐藏之前发送

UIKeyboardDidHideNotification    //键盘隐藏之后发送

UITextField 限制输入字数

UITextField 限制输入字数

方法一

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if (range.location>= 11)

        return NO;

    returnYES;

}

方法二

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (toBeString.length > 11) {

        textField.text = [toBeString substringToIndex:11];

        return NO;

    }

    returnYES;

}


当前光标位置 range.location

已选文字长度 range.length

输入文字长度 textView.text.length

已有文字长度 text.length
————mark 消息机制侦听更改 ----

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(textFieldChanged:)
                                             name:UITextFieldTextDidChangeNotification

                                           object:textField];

searchText = UITextField(frame: CGRect(x: interval_W, y: logoImageView.center.y+logoImageView.bounds.height*1.5, width: stageWidth*(500/640), height: stageWidth*(70/640)))
        searchText.layer.borderColor = violetColor.CGColor
        searchText.layer.borderWidth = 1.0
        searchText.layer.masksToBounds = true
        searchText.placeholder = "       请输入舞曲或者舞队名称"
        searchText.addTarget(self, action: "searchTextChange:", forControlEvents: UIControlEvents.EditingChanged)
        searchimage = UIImageView(image: UIImage(named: "ser_serch.png"))
        searchimage.center.x = searchimage.bounds.width
        searchimage.center.y = searchText.bounds.height/2//searchimage.bounds.height/2
        searchText.addSubview(searchimage)
        searchText.delegate = self
        searchText.clearButtonMode = UITextFieldViewMode.Always
        searchText.returnKeyType = UIReturnKeyType.Search
        self.view.addSubview(searchText)

-----
func searchTextChange(text:UITextField){
        if text.text == nil || text.text == ""{
           searchimage.hidden = false
        }else{
           searchimage.hidden = true
        }
    }

全局的取消键盘响应者
- (IBAction)View_TouchDown:(id)sender {

// 发送resignFirstResponder.


    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

UIApplication.sharedApplication().sendAction("resignFirstResponder", to: nil, from: nil, forEvent: nil)

UITextField的placeholder文字的位置,颜色等的自定义设置

From: https://www.jianshu.com/p/615145fe3801

首先想到的是如果系统默认的没有能改变的,那就自定义添加不同的重写该控件的方法

我们有时需要定制化UITextField对象的风格,可以添加许多不同的重写方法,来改变文本字段的显示行为。这些方法都会返回一个CGRect结构,制定了文本字段每个部件的边界范围,甚至修改placeHolder颜色,字体。

– textRectForBounds:   //重写来重置文字区域

– drawTextInRect:   //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.

– placeholderRectForBounds:  //重写来重置占位符区域

– drawPlaceholderInRect:  //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了

– borderRectForBounds:  //重写来重置边缘区域

– editingRectForBounds:  //重写来重置编辑区域

– clearButtonRectForBounds:  //重写来重置clearButton位置,改变size可能导致button的图片失真

– leftViewRectForBounds:

– rightViewRectForBounds:

通过– drawPlaceholderInRect:方法可改变placeHolder颜色、字体,请看代码:
首先定义一个类CustomTextField让它继承UITextField实现以下方法即可:

//控制清除按钮的位置
-(CGRect)clearButtonRectForBounds:(CGRect)bounds {
   return CGRectMake(bounds.origin.x + bounds.size.width - 50, bounds.origin.y + bounds.size.height -20, 16, 16);
}


//控制placeHolder的位置,左右缩20
-(CGRect)placeholderRectForBounds:(CGRect)bounds {
    
    //return CGRectInset(bounds, 20, 0);
   CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
   return inset;
}


//控制显示文本的位置
-(CGRect)textRectForBounds:(CGRect)bounds {
    //return CGRectInset(bounds, 50, 0);
    CGRect inset = CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
    return inset;
}


//控制编辑文本的位置
-(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;
}


//控制左视图位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds {
   CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
   return inset;
    //return CGRectInset(bounds,50,0);
}


//控制placeHolder的颜色、字体
- (void)drawPlaceholderInRect:(CGRect)rect
{
    //CGContextRef context = UIGraphicsGetCurrentContext();
    //CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
    [[UIColororangeColor] setFill];
    
    [[selfplaceholder] drawInRect:rectwithFont:[UIFontsystemFontOfSize:20]];
}

//下面是使用CustomTextField的代码,可放在viewDidLoad等方法中
_textField = [[CustomTextField alloc] initWithFrame:CGRectMake(20, 150, 280, 30)];
_textField.placeholder = @"手机号";
_textField.borderStyle = UITextBorderStyleRoundedRect;
_textField.textAlignment = UITextAlignmentLeft;
_textField.delegate = self;
_textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//_textField.text = @"随便";
UIImageView *imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"anyImage.png"]];
_textField.leftView = imgv;
_textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:_textField];

标签: 暂无
最后更新:2022年 11月 11日

陈昭

IT 程序员

打赏 点赞
< 上一篇
下一篇 >

文章评论

取消回复

COPYRIGHT © 2022 chenzhao. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang