创建实例,设置尺寸
let textField=UITextField(frame: CGRect(x: 95, y: 480, width: 200, height: 40))
view.addSubview(textField)
设置边框风格
- none 无边框
- line 直角矩形边界线
- bezel 有阴影的边框
- roundedRect 圆角矩形边框
textField.borderStyle = .line
设置文字颜色
textField.textColor=UIColor.green
设置对齐方式
textField.textAlignment = .center
设置提示文字
textField.placeholder="请输入姓名"
设置左右视图
// 左视图
let leftView = UILabel()
leftView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
leftView.text="持卡人"
leftView.textColor=UIColor.black
leftView.font=UIFont.systemFont(ofSize: 18)
// 右视图
let rightButton = UIButton(type: .infoDark)
rightButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
// 设置左右视图
textField.leftView=leftView
textField.rightView=rightButton
// 设置视图模式
textField.rightViewMode = .always
textField.leftViewMode = .always
设置右侧清除按钮
textField.clearButtonMode = .always
clearButtonMode的作用是控制右侧清除按钮什么时候显示,由枚举UITextFieldViewMode控制:
- never 从不显示
- whileEditing 开始编辑的时候
- unlessEditing 除了编辑外都出现
- always 一直出现
设置代理
- 首先添加协议头
class UIPage: UIViewController ,UITextFieldDelegate {
}
- 然后设置代理
textField.delegate=self
- 实现相关代理方法
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("将要开始编辑")
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("已经开始编辑")
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
print("将要结束编辑")
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("已经结束编辑")
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("文本输入内容将要发生变化(每次输入都会调用)")
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("将要清除输入内容,返回值是是否要清除掉内容")
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("将要按下Return按钮,返回值是是否结束输入(是否失去焦点)")
return true
}
设置完成按钮样式
textField.returnKeyType = UIReturnKeyType.done
设置键盘输入样式
- default 默认键盘:支持所有字符
- asciiCapable 支持ASCII的默认键盘
- numbersAndPunctuation 标准电话键盘,支持+*#等符号
- URL URL键盘,有.com按钮;只支持URL字符
- numberPad 数字键盘
- phonePad 电话键盘
- namePhonePad 电话键盘,也支持输入人名字
- emailAddress 用于输入电子邮件地址的键盘
- asciiCapableNumberPad 支持ASCII的数字键盘
- decimalPad 带‘.’的数字键盘
- twitter 功能齐全键盘,类似asciiCapable
- webSearch 带有面向url的附加的默认键盘类型
textField.keyboardType = UIKeyboardType.numberPad
设置键盘外观主题
- default 白色,这个字段是为了兼容以前的版本
- dark 黑色
- light 白色
- alert 黑色,这个字段是为了兼容以前的版本
textField.keyboardAppearance = UIKeyboardAppearance.light
设置安全文本(输入密码时使用)
textField.isSecureTextEntry = true
网友评论