-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutoCompleteTextField.swift
204 lines (176 loc) · 7.88 KB
/
AutoCompleteTextField.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//
// AutoCompleteTextField.swift
// AutocompleteTextfieldSwift
//
// Created by Mylene Bayan on 6/13/15.
// Copyright (c) 2015 mnbayan. All rights reserved.
//
import Foundation
import UIKit
open class AutoCompleteTextField:UITextField {
/// Manages the instance of tableview
fileprivate var autoCompleteTableView:UITableView?
/// Holds the collection of attributed strings
fileprivate lazy var attributedAutoCompleteStrings = [NSAttributedString]()
/// Handles user selection action on autocomplete table view
open var onSelect:(String, IndexPath)->() = {_,_ in}
/// Handles textfield's textchanged
open var onTextChange:(String)->() = {_ in}
/// Font for the text suggestions
open var autoCompleteTextFont = UIFont.systemFont(ofSize: 12)
/// Color of the text suggestions
open var autoCompleteTextColor = UIColor.black
/// Used to set the height of cell for each suggestions
open var autoCompleteCellHeight:CGFloat = 44.0
/// The maximum visible suggestion
open var maximumAutoCompleteCount = 3
/// Used to set your own preferred separator inset
open var autoCompleteSeparatorInset = UIEdgeInsets.zero
/// Shows autocomplete text with formatting
open var enableAttributedText = false
/// User Defined Attributes
open var autoCompleteAttributes:[String:AnyObject]?
/// Hides autocomplete tableview after selecting a suggestion
open var hidesWhenSelected = true
/// Hides autocomplete tableview when the textfield is empty
open var hidesWhenEmpty:Bool?{
didSet{
assert(hidesWhenEmpty != nil, "hideWhenEmpty cannot be set to nil")
autoCompleteTableView?.isHidden = hidesWhenEmpty!
}
}
/// The table view height
open var autoCompleteTableHeight:CGFloat?{
didSet{
redrawTable()
}
}
/// The strings to be shown on as suggestions, setting the value of this automatically reload the tableview
open var autoCompleteStrings:[String]?{
didSet{ reload() }
}
//MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
setupAutocompleteTable(superview!)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
commonInit()
setupAutocompleteTable(superview!)
}
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
commonInit()
setupAutocompleteTable(newSuperview!)
}
fileprivate func commonInit(){
hidesWhenEmpty = true
autoCompleteAttributes = [NSForegroundColorAttributeName:UIColor.black]
autoCompleteAttributes![NSFontAttributeName] = UIFont.boldSystemFont(ofSize: 12)
self.clearButtonMode = .always
self.addTarget(self, action: #selector(AutoCompleteTextField.textFieldDidChange), for: .editingChanged)
self.addTarget(self, action: #selector(AutoCompleteTextField.textFieldDidEndEditing), for: .editingDidEnd)
}
fileprivate func setupAutocompleteTable(_ view:UIView){
let screenSize = UIScreen.main.bounds.size
let tableView = UITableView(frame: CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.height, width: screenSize.width - (self.frame.origin.x * 2), height: 30.0))
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = autoCompleteCellHeight
tableView.isHidden = hidesWhenEmpty ?? true
view.addSubview(tableView)
autoCompleteTableView = tableView
autoCompleteTableHeight = 100.0
}
fileprivate func redrawTable(){
if let autoCompleteTableView = autoCompleteTableView, let autoCompleteTableHeight = autoCompleteTableHeight {
var newFrame = autoCompleteTableView.frame
newFrame.size.height = autoCompleteTableHeight
autoCompleteTableView.frame = newFrame
}
}
//MARK: - Private Methods
fileprivate func reload(){
if enableAttributedText{
let attrs = [NSForegroundColorAttributeName:autoCompleteTextColor, NSFontAttributeName:autoCompleteTextFont] as [String : Any]
if attributedAutoCompleteStrings.count > 0 {
attributedAutoCompleteStrings.removeAll(keepingCapacity: false)
}
if let autoCompleteStrings = autoCompleteStrings, let autoCompleteAttributes = autoCompleteAttributes {
for i in 0..<autoCompleteStrings.count{
let str = autoCompleteStrings[i] as NSString
let range = str.range(of: text!, options: .caseInsensitive)
let attString = NSMutableAttributedString(string: autoCompleteStrings[i], attributes: attrs)
attString.addAttributes(autoCompleteAttributes, range: range)
attributedAutoCompleteStrings.append(attString)
}
}
}
autoCompleteTableView?.reloadData()
}
func textFieldDidChange(){
guard let _ = text else {
return
}
onTextChange(text!)
if text!.isEmpty{ autoCompleteStrings = nil }
DispatchQueue.main.async(execute: { () -> Void in
self.autoCompleteTableView?.isHidden = self.hidesWhenEmpty! ? self.text!.isEmpty : false
})
}
func textFieldDidEndEditing() {
autoCompleteTableView?.isHidden = true
}
}
//MARK: - UITableViewDataSource - UITableViewDelegate
extension AutoCompleteTextField: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autoCompleteStrings != nil ? (autoCompleteStrings!.count > maximumAutoCompleteCount ? maximumAutoCompleteCount : autoCompleteStrings!.count) : 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "autocompleteCellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
if enableAttributedText{
cell?.textLabel?.attributedText = attributedAutoCompleteStrings[indexPath.row]
}
else{
cell?.textLabel?.font = autoCompleteTextFont
cell?.textLabel?.textColor = autoCompleteTextColor
cell?.textLabel?.text = autoCompleteStrings![indexPath.row]
}
cell?.contentView.gestureRecognizers = nil
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if let selectedText = cell?.textLabel?.text {
self.text = selectedText
onSelect(selectedText, indexPath)
}
DispatchQueue.main.async(execute: { () -> Void in
tableView.isHidden = self.hidesWhenSelected
})
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)){
cell.separatorInset = autoCompleteSeparatorInset
}
if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)){
cell.preservesSuperviewLayoutMargins = false
}
if cell.responds(to: #selector(setter: UIView.layoutMargins)){
cell.layoutMargins = autoCompleteSeparatorInset
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return autoCompleteCellHeight
}
}