您的位置:首页 > 移动开发 > Swift

swift 中UITextField 的详细介绍

2020-03-01 10:54 525 查看

1、文本输入框的创建#####

[code]let textField = UITextField(frame: CGRect(x:10, y:60, width:200, height:30))
// let textField = UITextField()
// textField.frame = CGRect(x:20,y:30,width:100,height:30)
//设置边框样式为圆角矩形
textField.borderStyle = UITextBorderStyle.roundedRect
self.view.addSubview(textField)

其中,文本输入框的边框样式有以下几种:
public enum UITextBorderStyle : Int {
case none 无边框
case line 直线边框
case bezel 圆角矩形边框
case roundedRect 边线+阴影
}

2、文本输入框的提示文字#####

[code]textField.placeholder = "请输入相关信息"

提示文字

3、文字大小超过文本框长度时自动缩小字号,而不是隐藏显示省略号#####

[code]textField.adjustsFontSizeToFitWidth=true  //当文字超出文本框宽度时,自动调整文字大小
textField.minimumFontSize=14  //最小可缩小的字号

4、水平/垂直对齐方式

[code]/** 水平对齐 **/
textField.textAlignment = .right //水平右对齐
textField.textAlignment = .center //水平居中对齐
textField.textAlignment = .left //水平左对齐

/** 垂直对齐 **/
textField.contentVerticalAlignment = .top  //垂直向上对齐
textField.contentVerticalAlignment = .center  //垂直居中对齐
textField.contentVerticalAlignment = .bottom  //垂直向下对齐

5、背景图片设置

[code]textField.borderStyle = .none //先要去除边框样式
textField.background = UIImage(named:"background1");

6、清除按钮(输入框内右侧小叉)#####

[code]textField.clearButtonMode = .whileEditing  //编辑时出现清除按钮
textField.clearButtonMode = .unlessEditing  //编辑时不出现,编辑后才出现清除按钮
textField.clearButtonMode = .always  //一直显示清除按钮

7,设置文本框关联的键盘类型#####

Default:系统默认的虚拟键盘
ASCII Capable:显示英文字母的虚拟键盘
Numbers and Punctuation:显示数字和标点的虚拟键盘
URL:显示便于输入url网址的虚拟键盘
Number Pad:显示便于输入数字的虚拟键盘
Phone Pad:显示便于拨号呼叫的虚拟键盘
Name Phone Pad:显示便于聊天拨号的虚拟键盘
Email Address:显示便于输入Email的虚拟键盘
Decimal Pad:显示用于输入数字和小数点的虚拟键盘
Twitter:显示方便些Twitter的虚拟键盘
Web Search:显示便于在网页上书写的虚拟键盘
使用样例:

[code]textField.keyboardType = UIKeyboardType.numberPad

8,使文本框在界面打开时就获取焦点,并弹出输入键盘

[code]textField.becomeFirstResponder()

9,使文本框失去焦点,并收回键盘

##########

[code]textField.resignFirstResponder()

10,设置键盘return键的样式

[code]textField.returnKeyType = UIReturnKeyType.done //表示完成输入
textField.returnKeyType = UIReturnKeyType.go //表示完成输入,同时会跳到另一页
textField.returnKeyType = UIReturnKeyType.search //表示搜索
textField.returnKeyType = UIReturnKeyType.join //表示注册用户或添加数据
textField.returnKeyType = UIReturnKeyType.next //表示继续下一步
textField.returnKeyType = UIReturnKeyType.send //表示发送

11,键盘return键的响应

[code]import UIKit
class ViewController: UIViewController,UITextFieldDelegate {

override func viewDidLoad() {
super.viewDidLoad()

let textField = UITextField(frame: CGRect(x:10,y:160,width:200,height:30))
//设置边框样式为圆角矩形
textField.borderStyle = UITextBorderStyle.roundedRect
textField.returnKeyType = UIReturnKeyType.done
textField.delegate=self
self.view.addSubview(textField)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//收起键盘
textField.resignFirstResponder()
//打印出文本框中的值
print(textField.text)
return true;
}
}

12、输入/显示文本字体的颜色#####

[code]textField.textColor = UIColor.cyan

13、文本框的字体大小设置#####

[code] //text.font = [UIFont fontWithName:@"Arial" size:20.0f];   //设置输入框内容的字体样式和大小
textField.font = UIFont.systemFont(ofSize: 14)

14、文本输入框的代理设置(遵守UITextFieldDelegate协议)#####

例子:class ViewController: UIViewController,UITextFieldDelegate {

[code]textField.delegate = self

15、输入框的背景颜色#####

[code]text.backgroundColor = [UIColor whiteColor];
//设置输入框的背景颜色,此时设置为白色 如果使用了自定义的背景图片边框会被忽略掉 ~~~
#####16、输入框中一开始就有的文字#####

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

[code]#####17、是否自动纠错#####

text.autocorrectionType = UITextAutocorrectionTypeNo;
有以下几种选择样式
typedef enum {
UITextAutocorrectionTypeDefault, 默认
UITextAutocorrectionTypeNo, 不自动纠错
UITextAutocorrectionTypeYes, 自动纠错
} UITextAutocorrectionType;

[code]#####18、再次编辑就清空#####

text.clearsOnBeginEditing = YES;

[code]#####19、首字母是否自动大写#####

text.autocapitalizationType = UITextAutocapitalizationTypeNone;
typedef enum {
UITextAutocapitalizationTypeNone, 不自动大写
UITextAutocapitalizationTypeWords, 单词首字母大写
UITextAutocapitalizationTypeSentences, 句子的首字母大写
UITextAutocapitalizationTypeAllCharacters, 所有字母都大写
} UITextAutocapitalizationType;

[code]#####20、键盘外观#####

textView.keyboardAppearance=UIKeyboardAppearanceDefault;
typedef enum {
UIKeyboardAppearanceDefault, 默认外观,浅灰色
UIKeyboardAppearanceAlert, 深灰 石墨色
} UIReturnKeyType;

[code]#####21、最右侧加图片是以下代码(左侧类似)#####

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

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

– textRectForBounds:   //重写来重置文字区域
– drawTextInRect:   //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
– placeholderRectForBounds:  //重写来重置占位符区域
– drawPlaceholderInRect:  //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
– borderRectForBounds:  //重写来重置边缘区域
– editingRectForBounds:  //重写来重置编辑区域
– clearButtonRectForBounds:  //重写来重置clearButton位置,改变size可能导致button的图片失真
– leftViewRectForBounds:
– rightViewRectForBounds:

[code]#####23、委托方法#####
  • (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;
    }
[code]#####24、通知#####
UITextField派生自UIControl,所以UIControl类中的通知系统在文本字段中也可以使用。除了UIControl类的标准事件,你还可以使用下列UITextField类特有的事件
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification
当文本字段退出编辑模式时触发。通知的object属性存储了最终文本。
因为文本字段要使用键盘输入文字,所以下面这些事件发生时,也会发送动作通知
UIKeyboardWillShowNotification   //键盘显示之前发送
UIKeyboardDidShowNotification    //键盘显示之后发送
UIKeyboardWillHideNotification   //键盘隐藏之前发送
UIKeyboardDidHideNotification    //键盘隐藏之后发送

//添加通知方法

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textFiledEditChanged:"), name: UITextFieldTextDidChangeNotification, object: textfield)

[code]#####25、限制只能输入特定的字符#####

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];//按cs分离出数组,数组按@""分离出字符串
BOOL canChange = [string isEqualToString:filtered];
return canChange;
}
上面这个NUMBERS是一个宏,可以在文件顶部定义:

define NUMBERS @”0123456789\n” (这个代表可以输入数字和换行,请注意这个\n,如果不写这个,Done按键将不会触发,如果用在SearchBar中,将会不触发Search事件,因为你自己限制不让输入\n,好惨,我在项目中才发现的。)

所以,如果你要限制输入英文和数字的话,就可以把这个定义为:

define kAlphaNum @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″。

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

[code]#####26、限制只能输入一定长度的字符#####
  • (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];
    [alert show];
    return NO;
    }
    }
    return YES;
    }
[code]此外:还有对于UITextField还有很多的用法:
例如:

//设置能不能进行编辑/用户交互的开关
textfield.enabled = true
textfield.userInteractionEnabled = true

//设置圆角属性
textField.layer.cornerRadius = 10.0
textField.layer.masksToBounds = true

//自定义输入源控件
let inputview = UIButton(frame: CGRectMake(0.0, 0.0, CGRectGetWidth(self.view.bounds), 100.0))
inputview.setImage(UIImage(named: "normalImage"), forState: UIControlState.Normal)
inputview.backgroundColor = UIColor.lightGrayColor()
inputview.addTarget(self, action: Selector("click:"), forControlEvents: UIControlEvents.TouchUpInside)
textfield.inputView = inputview

// 自定义输入源控件副视图
let accessoryview = UIView(frame: CGRectMake(0.0, 0.0, CGRectGetWidth(self.view.bounds), 40.0))
accessoryview.backgroundColor = UIColor.greenColor()
let accessoryLeft = UIButton(frame: CGRectMake(10.0, 10.0, 60.0, 20.0))
accessoryview.addSubview(accessoryLeft)
accessoryLeft.setTitle("取消", forState: UIControlState.Normal)
accessoryLeft.backgroundColor = UIColor.orangeColor()
accessoryLeft.addTarget(self, action: Selector("leftClick:"), forControlEvents: UIControlEvents.TouchUpInside)
let accessoryRight = UIButton(frame: CGRectMake((CGRectGetWidth(accessoryview.bounds) - 10.0 - 60.0), 10.0, 60.0, 20.0))
accessoryview.addSubview(accessoryRight)
accessoryRight.setTitle("确定", forState: UIControlState.Normal)
accessoryRight.backgroundColor = UIColor.orangeColor()
accessoryRight.addTarget(self, action: Selector("rightClick:"), forControlEvents: UIControlEvents.TouchUpInside)
textfield.inputAccessoryView = accessoryview

// 自定义输入源控件时响应事件
// MARK: - click
func click(button:UIButton)
{
self.view.endEditing(true)
}

//MARK: - left/right click
func leftClick(button:UIButton)
{
print("取消")
}
func rightClick(button:UIButton)
{
self.view.endEditing(true)
print("确定")
}


转载至
作者:刘高见
链接:https://www.jianshu.com/p/63bdeca39ddf
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
tan诺 发布了1 篇原创文章 · 获赞 1 · 访问量 310 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: