ios - 以编程方式快速将搜索栏添加到 TableView

标签 ios swift uitableview cocoa-touch uisearchbar

我有一个文本字段,它代表一个 TableView 作为它的输入 View 。我想向该 TableView 添加 2 个内容。

1) 添加搜索栏。
2) 在tableview顶部添加取消按钮。

class enterYourDealVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating {
var tableView: UITableView  =   UITableView()
let searchController = UISearchController(searchResultsController: nil)

var dealAirports = [
    airPorts(name: "Airport1", shortcut: "AP1")!),
    airPorts(name: "Airport2", shortcut: "AP2")!)
]
var filteredAirports = [airPorts]()


//view did load
    tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar
    toTextField.inputView = self.tableView

//here is my search function
func filterContentForSearchText(searchText: String, scope: String = "All") {
    filteredAirports = dealAirports.filter { ap in
        return ap.name.lowercaseString.containsString(searchText.lowercaseString)
    }

    tableView.reloadData()
}
}

问题在于此代码,它不进行搜索。此外,当我单击搜索栏时,它会关闭 tableview 并将我返回到 viewcontroller。我该如何解决这个问题?

如何向该表格 View 添加取消按钮?

最佳答案

这将添加一个 SeachBar

lazy var searchBar:UISearchBar = UISearchBar()

override func viewDidLoad()
{
     searchBar.searchBarStyle = UISearchBar.Style.default
    searchBar.placeholder = " Search..."
    searchBar.sizeToFit()
    searchBar.isTranslucent = false
    searchBar.backgroundImage = UIImage()
    searchBar.delegate = self
    navigationItem.titleView = searchBar

}

func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)
{
    ...your code...
}

关于ios - 以编程方式快速将搜索栏添加到 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508720/

相关文章:

ios - 将字符串从 TableView 单元格传递到 Swift 3 中的 View Controller

ios - 如何从服务器获取 AFNetworking 中的完整响应字符串?

ios - 首次启动模拟器时,ViewController 无法正确重新加载

ios - 选项卡栏 Controller 根据登录隐藏选项卡 - 使用 Storyboard

ios - PresentViewController 不工作

swift - 如何仅设置左下角、右下角和左上角的图层角半径?

ios - 转到新场景后背景音乐暂停 Swift 3 SpriteKit

ios - Swift 中的大型 Core Data 批量插入导致内存泄漏

ios - 将随机元素添加到数组(swift)

ios - UITableViewController 不会调用 cellForRowAtIndexPath 但 numberOfSectionsInTableView 和 numberOfRowsInSection 设置正确