有人能够在swift中帮助解决以下问题:
我基本上试图创建一个下拉列表
这是我的代码
import UIKit
var names = ["frank", "john", "harry", "mike", "jones"]
var filtered:[String] = []
class ViewController: UIViewController {
var searchActive : Bool = false
@IBOutlet weak var searchText: UITextField!
@IBOutlet weak var personTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
personTable.alpha = 0
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func searchTextClick(sender: AnyObject) {
if(personTable.alpha == 0){
personTable.alpha = 1
searchActive = true;
searchText(searchText, textDidChange: "")
}else{
personTable.alpha = 0
searchActive = false;
}
}
func tableView(personTable: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return names.count;
}
func tableView(personTable: UITableView!,
cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
cell.textLabel!.text = names[indexPath.row]
return cell
}
func searchText(searchText: UITextField, textDidChange newSearch: String) {
let filteredArr = names.filter{$0.containsCharacters(searchText.text)}
self.personTable.reloadData()
}
}
extension String {
func containsCharacters(ch:String)-> Bool{
var err:NSError?
let reg = NSRegularExpression(pattern: ch, options: NSRegularExpressionOptions.CaseInsensitive, error: &err)
if let matches = reg?.matchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0,count(self))) where matches.count != 0 {
return true
}
return false
}
}
THX
答案 0 :(得分:1)
出于好的理由,iOS中不存在下拉列表。 您应该使用UIPickerView或添加一个搜索字段到您的tableview。 在后一个示例中,您应该实现UISearchBarDelegate 并使用其中一个委托方法来执行操作。可能看起来像这样
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
self.filteredDkStationsKeys = self.allDkStationsKeys
}else{
self.filteredDkStationsKeys.removeAll(keepCapacity: false)
self.filteredDkStationsKeys = self.allDkStationsKeys.filter { ( $0.lowercaseString.hasPrefix(searchText.lowercaseString) ) }
}
self.tableView.reloadData()
}
您可以使用自己的过滤器功能替换过滤器内容(我在表中显示filteredDkStations)。这将为您提供一个越来越小的表,因为越来越少的文本与搜索输入匹配。看起来很棒!