UITextField - 文本框
继承关系
- NSObject ->UIResponder -> UIView ->UIControl -> UITextField
概述
文本框允许用户输入一行文本到一个应用程序。您通常使用文本框来收集用户的少量信息,并执行一些任务,例如基于该文本搜索操作。
初始化及设置样式
- 初始化
textField = UITextField(frame: CGRect(x: 100,y: 100,width: 150,height: 30))
- 设置文字
textField.text = “welcome”
- 设置占位符
textField.placeholder = “Placeholder”
- 设置属性文本
textField.attributedText = NSAttributedString(string: " 欢迎", attributes: [NSForegroundColorAttributeName : UIColor.redColor(),NSFontAttributeName: UIFont.systemFontOfSize(20)])
- 设置属性文本占位符
textField.attributedPlaceholder = NSAttributedString(string: " 占位符", attributes: [NSForegroundColorAttributeName : UIColor.grayColor(),NSFontAttributeName: UIFont.systemFontOfSize(15)])
- 设置字体
textField.font = UIFont.boldSystemFontOfSize(20)
- 设置文本自适应文本框的宽度,同时设置文本最小字体
textField.adjustsFontSizeToFitWidth = true
textField.minimumFontSize = 12
- 设置文本颜色
textField.textColor = UIColor.blueColor()
- 文本对其方式
textField.textAlignment = NSTextAlignment.Left
//对齐方式定义如下:
enum NSTextAlignment : Int {
case Left // 左对齐
case Center // 居中对齐
case Right // 右对齐
case Justified // 完全为文本对齐, 以便在段落的最后一行是自然对齐的
case Natural // 使用当前本地应用程序的默认对齐方式
- 设置文本边框类型
textField.borderStyle = UITextBorderStyle.RoundedRect
//类型定义如下
enum UITextBorderStyle : Int {
case None //无边框
case Line //线型边框
case Bezel //线性边框带阴影
case RoundedRect //圆角边框
}
- 设置活动状态/禁用状态背景
textField.background = UIImage(named: "background")
textField.disabledBackground = UIImage(named: "bg")
编辑文本
- 获取文本是否正在编辑, 如果正在编辑返回true,否则返回false,属性只读。
let isEditing = textField.editing
- 当选择文本框开始编辑的时候,是否删除旧文本
textField.clearsOnBeginEditing = true
- true:文本定位光标不显示,用户输入的文字时会替换掉文本框内的旧文本,并把此属性设置为false
textField.clearsOnInsertion = true //此属性很少用到
//是否允许用户编辑文本框内文本的样式信息
textField.allowsEditingTextAttributes = true
禁止编辑
允许编辑
管理 overlay views
- 定义覆盖视图在文本框的显示时机
enum UITextFieldViewMode : Int {
case Never //从不显示
case WhileEditing //当编辑的时候显示
case UnlessEditing // 除了编辑状态,其他状态显示
case Always //总显示
}
- 设置清楚按钮(“x”型按钮在文本框右侧)的显示模式
textField.clearButtonMode = UITextFieldViewMode.Always
- 设置文本左侧视图
let leftOverLayButton = UIButton(type: .DetailDisclosure)
leftOverLayButton.frame = CGRect(x: 0, y: 0, width: 28, height: 38)
textField.leftView = leftOverLayButton
textField.leftViewMode = UITextFieldViewMode.WhileEditing
- 设置文本右侧视图
let rightOverLayButton = UIButton(frame: CGRect(x: 0,y: 0,width: 25,height: 25))
rightOverLayButton.setImage(UIImage(named: "close"), forState: UIControlState.Normal)
textField.rightView = rightOverLayButton
textField.rightViewMode = UITextFieldViewMode.Never
替换系统输入视图(软键盘)
- 设置文本框的输入视图
textField.inputView = UIImageView(image: UIImage(named: "11"))
- 设置文本框的输入辅助视图
let toolBar = UIToolbar(frame: CGRectMake(0,0,200,50))
let item = UIBarButtonItem(title: "item", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
toolBar.setItems([item], animated: false)
//输入视图的辅助视图,默认在键盘视图的上面;如果提供了inputView,那么在其上面。
textField.inputAccessoryView = toolBar
配置键盘的外观
应为UITextField
遵循UITextInputTraits
协议,你可以用其属性配置文本框的键盘。
- 配置键盘字符自动大写
textField.autocapitalizationType = UITextAutocapitalizationType.None
enum UITextAutocapitalizationType : Int {
case None //不大写
case Words //每个单词的第一个字母大写
case Sentences //每个句子的第一个字母大写
case AllCharacters //所有字符大写
}
- 文本自动更正
textField.autocorrectionType = UITextAutocorrectionType.Default
enum UITextAutocorrectionType : Int {
case Default //默认,为当前系统指定合适的更正功能
case No //禁用自动更正功能
case Yes //开启自动更正功能
}
- 拼写检查
textField.spellCheckingType = UITextSpellCheckingType.Default
enum UITextSpellCheckingType : Int {
case Default //指定默认拼写检查行为。默认行为是使拼写检查时同时启用自动校正。
case No //禁用拼写检查
case Yes //启用拼写检查
}
- 键盘类型
textField.keyboardType = UIKeyboardType.NumberPad
enum UIKeyboardType : Int {
case Default // 默认
case ASCIICapable // 标准ASCII符号键盘
case NumbersAndPunctuation // 数字和标点符号
case URL //URL样式键盘.com /
case NumberPad //数字键盘
case PhonePad //电话键盘
case NamePhonePad //电话键盘,也支持输入人名
case EmailAddress //用于输入电子 邮件地址的键盘
case DecimalPad //数字键盘 有数字和小数点
case Twitter //优化的键盘,方便输入@、#字符
case WebSearch //一个优化的网页搜索字词和网址输入
static var Alphabet: UIKeyboardType { get }//已禁用,用.ASCIICapable代替。
}
- 配置键盘外观
textField.keyboardAppearance = UIKeyboardAppearance.Light
enum UIKeyboardAppearance : Int {
case Default //默认为 .Light
case Dark //暗色
case Light //亮色
static var Alert: UIKeyboardAppearance { get } //已禁用,用.Dark代替。
}
- 配置返回按钮显示的文字
textField.returnKeyType = UIReturnKeyType.EmergencyCall
enum UIReturnKeyType : Int {
case Default //显示return
case Go //显示Go
case Google //显示search
case Join //显示Join
case Next //显示Next
case Route //显示Route(路线)
case Search //显示search
case Send //显示Send
case Yahoo //显示search
case Done //显示Done
case EmergencyCall //显示EmergencyCall(紧急呼叫)
case Continue //显示Continue
}
重载方法
下面方法不能直接调用,必须子类化UITextField
,然后重写这写方法对文本框的元素的位置和大小进行定制。
//文本框的文本绘制区域
func textRectForBounds(_ bounds: CGRect) -> CGRect
//在指定的区域绘制文本
func drawTextInRect(_ rect: CGRect)
返回文本框占位符的绘制区域
func placeholderRectForBounds(_ bounds: CGRect) -> CGRect
//在指定的区域绘制占位符
func drawPlaceholderInRect(_ rect: CGRect)
//返回边框区域
func borderRectForBounds(_ bounds: CGRect) -> CGRect
//返回可编辑文本的区域
func editingRectForBounds(_ bounds: CGRect) -> CGRect
//返回创建清除按钮的区域
func clearButtonRectForBounds(_ bounds: CGRect) -> CGRect
//返回左侧视图区域
func leftViewRectForBounds(_ bounds: CGRect) -> CGRect
//返回右侧视图区域
func rightViewRectForBounds(_ bounds: CGRect) -> CGRect
delegate
使用 UITextFieldDelegate
协议管理编辑和验证文本对象,它的所有方法都是可选的。
文本编辑流程
引用官方文档,下面翻译成中文。
Before becoming the first responder, the text field calls its delegate’s textFieldShouldBeginEditing: method. Use that method to allow or prevent the editing of the text field’s contents.
在变为第一响应者之前,文本框调用代理的方法
textFieldShouldBeginEditing:
。用此方法来允许或禁止编辑文本框的内容。The text field becomes the first responder.
文本框成为第一响应者
In response, the system displays the keyboard (or the text field’s input view) and posts the
UIKeyboardWillShowNotification
andUIKeyboardDidShowNotification
notifications as needed. If the keyboard or another input view was already visible, the system posts theUIKeyboardWillChangeFrameNotification
andUIKeyboardDidChangeFrameNotification
notifications instead.系统展示一个键盘(或者文本输入视图)并且发送
UIKeyboardWillShowNotification
和UIKeyboardDidShowNotification
消息通知作为回应。如果键盘或另外的输入视图已经显示,系统会发送
UIKeyboardWillChangeFrameNotification
和UIKeyboardDidChangeFrameNotification
通知来代替。The text field calls its delegate’s
textFieldDidBeginEditing:
method and posts aUITextFieldTextDidBeginEditingNotification
notification.文本框调用代理的
textFieldDidBeginEditing:
方法并且发送UITextFieldTextDidBeginEditingNotification
通知。The text field calls various delegate methods during editing:
在编辑文本框时调用代理的各种方法- Whenever the current text changes, it calls the
textField:shouldChangeCharactersInRange:replacementString:
method and posts theUITextFieldTextDidChangeNotification
notification.
无论当前文本内容什么时候变化,它都会调用
textField:shouldChangeCharactersInRange:replacementString:
方法并且发送UITextFieldTextDidChangeNotification
通知。- It calls the
textFieldShouldClear:
method when the user taps the built-in button to clear the text.
当用户点击文本框内建的清除按钮的时候,调用代理方法
textFieldShouldClear:
。- It calls the
textFieldShouldReturn:
method when the user taps the keyboard’s return button.
当用户点击键盘的return按钮的时候,调用代理方法
textFieldShouldReturn:
。- Whenever the current text changes, it calls the
Before resigning as first responder, the text field calls its delegate’s
textFieldShouldEndEditing:
method. Use that method to validate the current text.在释放第一响应者之前,文本框调用代理方法
textFieldShouldEndEditing:
。可以用此方法来验证当前的文本内容。The text field resigns as first responder.
文本框释放第一响应者
In response, the system hides or adjusts the keyboard as needed. When hiding the keyboard, the system posts theUIKeyboardWillHideNotification
andUIKeyboardDidHideNotification
notifications.系统会根据需要隐藏或者调整键盘来作为回应。当隐藏键盘时,系统发送
UIKeyboardWillHideNotification
和UIKeyboardDidHideNotification
通知。The text field calls its delegate’s
textFieldDidEndEditing:
method and posts aUITextFieldTextDidEndEditingNotification
notification.文本框调用代理
textFieldDidEndEditing:
方法并且发送UITextFieldTextDidEndEditingNotification
通知。
代理方法
指明特定文本是否应该开始编辑
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
告诉代理文本已经开始编辑,可以更新状态信息或执行其它的任务,比如编辑状态显示
overlay views
。func textFieldDidBeginEditing(_ textField: UITextField)
询问代理编辑行为是否应该结束
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
告诉代理文本编辑行为已经结束,当文本框
resigns first responder
的时候调用此方法。func textFieldDidEndEditing(_ textField: UITextField)
指定的文本范围是否应该被更换,true被更换,false保留旧文本。
文本变化的时候会调用此方法,可以用此方法验证用户的输入。例如:只让用户输入除了数字的其它字符。func textField(_ textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool指明是否清除内容文本框的内容。当点击文本框内建
清除按钮
的时候调用,或用户开始编辑并且clearsOnBeginEditing = true
的时候调用。func textFieldShouldClear(_ textField: UITextField) -> Bool
询问代理是否处理用户按下return按钮这种行为,当用户点击return按钮的时候调用此方法,如果想隐藏键盘可调用resignFirstResponsder方法。
func textFieldShouldReturn(_ textField: UITextField) -> Bool