IPTextField
IPTextField是一个自定义UIView子类,允许用户轻松输入IP地址。IP地址在输入过程中进行验证。
此库确保
- 只能输入0-255之间的数字
- 当一个字段填写后,下一个字段将自动激活
- 一个键盘工具栏,易于在字段间切换
使用IPTextField
通过代码
import IPTextField
let ipTextField = IPTextField()
通过Storyboard
拖拽一个UIView并更改类属性
自定义 IPTextField
通过故事板
可以通过界面构建器和/或代码更改的属性有
- 行颜色
- 文本颜色
- 边框颜色
- 边框宽度
- 圆角半径
通过代码
可以通过代码更改的属性有
- 字体
- 文本对齐
ipTextField.lineColor = UIColor.red
ipTextField.textColor = UIColor.purple
ipTextField.borderColor = UIColor.blue
ipTextField.borderWidth = 10
ipTextField.cornerRadius = 10
ipTextField.font = .systemFont(ofSize: 30)
ipTextField.textAlignment = .left
方法
插入文本的方法
使用方法 insertText(at position: Int, text: String)
在 IPTextField 的特定位置插入文本
try! ipTextField.insertText(at: 0, text: "11")
使用方法 insertText(part1: String, part2: String, part3: String, part4: String)
在整个 IPTextField 中插入文本
try! ipTextField.insertText(part1: "32", part2: "121", part3: "11", part4: "0")
获取文本的方法
使用方法 text(at position: Int)
从 IPTextField 的特定位置获取文本
let text = try! ipTextField.text(at: 0)
使用方法 text()
以 IP 地址格式从 IPTextField 获取文本
let text2 = ipTextField.text()
检查ip文本字段的state方法
使用isEmpty()
方法检查IPTextField是否为空
let isEmpty = ipTextField.isEmpty()
使用isCompleted()
方法检查IPTextField是否已完成
let isCompleted = ipTextField.isCompleted()
清除ip文本字段中的文本方法
使用clear(at position: Int)
方法从文本字段中删除特定位置的文本
try! ipTextField.clear(at: 0)
使用clear()
方法从IPTextField中删除文本
ipTextField.clear()
错误处理
将某些文本插入到IPTextField的所有方法,如果该文本包含非数字字符,将引发错误
do {
try ipTextField.insertText(at: 0, text: "aa")
} catch {
let description = error.localizedDescription //Only digits are allowed
}
接受位置参数的所有方法,如果位置小于0或大于3,将引发错误
do {
try ipTextField.insertText(at: 9, text: "111")
} catch {
let description = error.localizedDescription //Position must be between 0 and 3
}
将某些文本插入到IPTextField的所有方法,如果该文本包含大于255的数字,将引发错误
do {
try ipTextField.insertText(at: 0, text: "256")
} catch {
let description = error.localizedDescription //Value can not be greater than 255
}
IPTextFieldDelegate
如果要在插入完成后接收通知,将委托分配给IPTextField
ipTextField.delegate = self
使所需的对象遵循IPTextFieldDelegate
协议并实现insertDone()
方法
extension ViewController: IPTextFieldDelegate {
func insertDone() {
print("insert is finished")
}
}