【发布时间】:2019-02-28 10:35:33
【问题描述】:
我有一个 textField,当触摸它时会显示一个带有一些行的 tableView。
我正在尝试这样做:当用户选择其中一行时,row 的值被放置在 textField 中并且 tableView 被关闭。
第一部分对我来说效果很好。用户触摸一行,textField 显示该行的值。但是如果我想关闭 tableview,我必须在行上按两次。
这是我的代码:
class Redactar_mensaje: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var values = ["123 Main Street", "789 King Street", "456 Queen Street", "99 Apple Street", "red", "orange", "yellow", "green", "blue", "purple", "owaldo", "ostras", "Apple", "Pineapple", "Orange", "Adidas"]
@IBOutlet weak var campo_para: UITextField!
@IBOutlet weak var tableView: UITableView!
var originalCountriesList:[String] = Array()
override func viewDidLoad() {
super.viewDidLoad()
tableView.isHidden = true
for country in values {
originalCountriesList.append(country)
}
campo_para.delegate = self
tableView.delegate = self
tableView.dataSource = self
campo_para.addTarget(self, action: #selector(textFieldActive), for: UIControlEvents.touchDown)
campo_para.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
}
@objc func searchRecords(_ textField: UITextField) {
self.values.removeAll()
if textField.text?.count != 0 {
for country in originalCountriesList {
if let countryToSearch = textField.text{
let range = country.lowercased().range(of: countryToSearch, options: .caseInsensitive, range: nil, locale: nil)
if range != nil {
self.values.append(country)
}
}
}
} else {
for country in originalCountriesList {
values.append(country)
}
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellx")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cellx")
}
cell?.textLabel?.text = values[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
campo_para.text = values[indexPath.row]
tableView.isHidden = true //I need press twice for this. I want press only one
}
func textFieldActive() {
tableView.isHidden = false
}
}
理想情况下,用户触摸 textField,显示 tableView,选择其中一个值,然后自动关闭 tableView。但这最后一个效果不佳。
有什么建议吗?
【问题讨论】:
-
我认为您需要搜索功能。为此使用
UISearchBar或UISearchController,这将是您满足您要求的完美选择。在 searchbar 的委托方法中 - 在 searchBarBeginEditing 上 - 您可以显示 tableview 并单击 tableview 单元格,您可以隐藏 tableview。
标签: swift uitableview swift3 autocomplete