swift 中 UITextfield创建
1、创建
let textField = UITextField.init(frame: CGRect.init(x: 10, y: 160, width: 200, height: 30))
textField.backgroundColor = UIColor.orange
textField.borderStyle = .roundedRect
self.view.addSubview(textField)
2、 边框样式
UITextBorderStyle.none // 无边框
UITextBorderStyle.roundedRect // 圆角矩形边框
UITextBorderStyle.line //直线边框
UITextBorderStyle.bezel //边线+阴影
3、设置文本样式
textField.placeholder = "请输入。。。" //没有输入的时候,进行提示文字
textField.text = "hello" //默认的输入文字
textField.textColor = UIColor.red // 文字颜色
textField.adjustsFontSizeToFitWidth = true //文字自动调整大小
textField.minimumFontSize = 14 //设置的最小字号
//水平对齐方式
textField.textAlignment = NSTextAlignment.left //文字文字,自己根据需要设置文字位置
//垂直对齐方式
textField.contentVerticalAlignment = UIControlContentVerticalAlignment.center //包括:.Top向上对齐 ; .Bottom 向下对齐
4、键盘设置
textField.returnKeyType = UIReturnKeyType.done
.done //暗示用户输入完成
.go //暗示用户输入完成并会跳转到另一页
.search //暗示用户用刚才输入的文字做关键字进行搜索
.join //暗示用户会注册用户或者是其他添加数据的操作
.next //暗示用户进行下一步
.send //暗示用户发送信息
5、自定义键盘
let view1 = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
textField.inputView = view1 //自定义设置,替代系统键盘
let view2 = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 200))
textField.inputAccessoryView = view2 //可与自定义键盘一起使用,也可与系统键盘一起使用
6、代理方法
首先设置代理 UITextFieldDelegate
textField.delegate = self
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder() //键盘回收
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
//编辑开始前被调用,如果返回时false编辑将不会开始
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//文本修改前被调用,range为改变范围,string 中传入修改后的字符串,返回false,修改将不会被反映
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
//编辑开始后被调用
}
func textFieldDidEndEditing(_ textField: UITextField) {
//编辑结束后被调用
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
//文本框中清除按钮被触摸时候调用,此时返回true将清除内容,返回false保持原样
return true
}
7、清除按钮
textField.clearButtonMode = UITextFieldViewMode.whileEditing
.whileEditing //编辑时出现清除按钮
.unlessEditing //编辑完成后出现清除按钮
.always //总是出现清除按钮
8、背景设置
textField.background = UIImage.init(named: "图片名称") // 如果边框存在样式这句话无效