UITextField相关

初始化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];

设置背景

注意: 只有在 UITextBorderStyleNone 样式下,设置背景图才会生效,且图片大小小于 text 的frame时,图片会拉伸

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

设置enable为NO 时的背景图片

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;

内容的垂直对齐方式

text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

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

textFied.adjustsFontSizeToFitWidth = YES;
//设置自动缩小显示的最小字体大小,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;
**/

给弹出的键盘添加一个菜单栏,并放置按钮

UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,44)];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 60, 7,50, 30)];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setTitle:@"完成"forState:UIControlStateNormal];
[bar addSubview:button];
textField.inputAccessoryView = bar;

更改TextField弹出的键盘为其他控件

//比如弹出一个时间选择器
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;

self.inputView = datePicker;

首字母是否大写

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;
**/

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

UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
text.rightView=image;
text.rightViewMode = UITextFieldViewModeAlways; 
/**
typedef enum {
    UITextFieldViewModeNever,
    UITextFieldViewModeWhileEditing,
    UITextFieldViewModeUnlessEditing,
    UITextFieldViewModeAlways
} UITextFieldViewMode;
**/

成为第一响应者

[textField becomeFirstResponder];

取消作为第一响应者

[textField resignFirstResponder];

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

//只有这三个
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification

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

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

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

限制只能输入特定的字符

#define NUMBERS @”0123456789n” 

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSCharacterSet *cs;
    //invertedSet方法是去反字符,把所有的除了NUMBERS 里的字符都找出来(包含去空格功能)

    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];

    // componentsJoinedByString 用于根据一个字符串来将数组连接成一个新的字符串。
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串

    BOOL canChange = [string isEqualToString:filtered];

    return canChange;
    //这样写了以后,输入非数字时不能输入
}

上面那个NUMBERS是一个宏,可以在文件顶部定义:

(这个代表可以输入数字和换行,请注意这个n,如果不写这个,Done按键将不会触发,如果用在SearchBar中,将会不触发Search事件,因为你自己限制不让输入n,好惨,我在项目中才发现的。) 所以,如果你要限制输入英文和数字的话,就可以把这个定义为:

#define kAlphaNum   @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″。

当然,你还可以在以上方法return之前,做一提示的,比如提示用户只能输入数字之类的。如果你觉得有需要的话。

限制只能输入一定长度的字符

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; 
{ 
    //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
   if ([string isEqualToString:@"n"]) //按会车可以改变 //这里这个字符写什么,就只能输入什么
    { 
        return YES; 
    } 

    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容

    if (self.myTextField == textField) //判断是否时我们想要限定的那个输入框
    { 
        if ([toBeString length] > 20) //如果输入框内容大于20则弹出警告
        { 
            textField.text = [toBeString substringToIndex:20]; 
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease]; //iOS8.3以后用 
    UIAlertController
            [alert show]; 

            /* iOS9后的Alert
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示"message:@"超过最大字数不能输入了"preferredStyle:UIAlertControllerStyleActionSheet];
            [selfpresentViewController:alertViewanimated:YEScompletion:nil];
            */
            return NO; 
        } 
    } 
    return YES; 
}

UITextFieldDelegate

//控制当前输入框是否能被编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;

//开始编辑,当输入框开始时触发,并成为第一响应者
- (void)textFieldDidBeginEditing:(UITextField *);

//询问输入框是否可以结束编辑,键盘是否可以收回
- (BOOL)textFieldShouldEndEditing:(UITextField *);

//当前输入框结束编辑时触发,键盘收回之后触发
- (void)textFieldDidEndEditing:(UITextField *)textField;

//当前输入框结束编辑时触发,键盘收回之后触发,并附带结束的原因信息
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason;

//是否允许改变文本内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;

//控制输入框清除按钮是否有效
- (BOOL)textFieldShouldClear:(UITextField *)textField;

//控制键盘是否在按下键盘return时回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField;

使用其他UIView充当输入键盘,比如UIPickView

#import "ZFHeadImageField.h"

#define ROW_HEIGHT 120

@interface ZFHeadImageField()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (strong, nonatomic) NSArray *dataArray;

@property (strong, nonatomic) UIPickerView *picker;

@end

@implementation ZFHeadImageField

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self showKeyboard];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self showKeyboard];
}

- (NSArray*)dataArray
{
    if(_dataArray == nil)
    {
        _dataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"headImage" ofType:@"plist"]];
    }
    return _dataArray;
}

- (void)setText:(NSString *)text
{
    [super setText:text];

    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:text]];
    NSLog(@"%f,%f",self.frame.size.width, self.frame.size.height);
    imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.rightView = imageView;
    self.rightViewMode = UITextFieldViewModeAlways;
}

- (void)showKeyboard
{
    self.picker = [[UIPickerView alloc]init];
    self.inputView = self.picker;

    self.picker.dataSource = self;
    self.picker.delegate = self;

    if(self.text.length == 0)
    {
        self.text = self.dataArray[0];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.dataArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return ROW_HEIGHT;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
{
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",self.dataArray[row]]]];
    imageView.frame = CGRectMake(0, 0, 100, 100);
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    return imageView;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.text = [NSString stringWithFormat:@"%@",self.dataArray[row]];
}

@end

iOS判断输入框不为空格以及空

//判定输入框不为空格以及空
NSString *self.textField=[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([self.textField length] == 0) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"内容不能为空!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
    return NO;
}

results matching ""

    No results matching ""