自动完成字段
UITextField
的子类,在输入时显示内联建议。
需求
- iOS 10.0+
- Swift 4.2+
安装
CocoaPods
将以下内容添加到您的 Podfile
target 'MyApp' do
pod 'AutocompleteField', '~> 2.0'
end
Swift 包管理器
- 选择 文件 > Swift 包 > 添加包依赖。
- 在 选择包仓库 对话框中输入
https://github.com/filipstefansson/AutocompleteField.git
。
有关更多信息,请参阅 Apple 文档。
手动操作
- 将
/Sources/AutocompleteField.swift
复制到您的项目中。没有其他依赖项。
使用方法
您可以用与常规 UITextField
相同的方式使用此文本字段,通过 Storyboards 或编程方式。
基本
import AutocompleteField
...
let textfield = AutocompleteField(frame: CGRect(x: 20, y: 20, width: 200, height: 40))
textfield.placeholder = "Name"
textfield.suggestions = [
"George Washington",
"Thomas Jefferson",
"John Adams",
"Theodore Roosevelt",
"John F. Kennedy",
"George W. Bush",
]
self.view.addSubview(textfield)
分隔符
分隔符可以用来在找到特定字符后提示自动完成。在此示例中,我们查找 @
字符,然后提供电子邮件提供商的提示。
import AutocompleteField
...
// email textfield autocompleting email providers
let textfield = AutocompleteField(frame: CGRect(x: 20, y: 20, width: 200, height: 40))
textfield.placeholder = "Email"
textfield.keyboardType = .emailAddress
textfield.suggestions = [
"gmail.com",
"icloud.com",
"outlook.com",
]
// add the delimiter
textfield.delimiter = "@"
self.view.addSubview(textfield)
API
属性 | 类型 | 描述 |
---|---|---|
suggestionColor |
UIColor |
建议的颜色。默认为默认占位符颜色。 |
suggestion |
String |
当前显示的建议。只读。 |
suggestions |
字符串 |
建议数组 |
建议类型 |
SuggestionType |
应使用的建议类型。代码.Word 将仅提示建议中的下一个单词,而.Sentence 将显示整个建议。默认为.Sentence 。 |
像素修正值 |
CGPoint |
移动建议标签的上下左右位置。如果建议与输入值不匹配,请使用此选项进行纠正。 |
水平间距 |
CGFloat |
为您的textfield添加内边距。在具有填充的borderStyle 中使用时自动设置。 |
分隔符 |
String |
仅当分隔符出现多次时才显示建议。非常适合自动完成电子邮件提供商。 |
演示
查看示例项目。
授权协议
AutocompleteField
在MIT授权协议下提供。见LICENSE
了解更多。