如何在单击搜索栏时显示表格视图?

时间:2017-08-27 19:16:00

标签: ios iphone swift xcode uitableview

我只想在点击搜索栏时显示表格视图(如instagram)。如果有人知道如何做到这一点,任何信息都会有所帮助。

以下是我的相关代码:

class UserSearchController: UICollectionViewController, UICollectionViewDelegateFlowLayout,UISearchBarDelegate, UISearchDisplayDelegate {

let cellId = "cellId"

let searchBar: UISearchBar = {
    let sb = UISearchBar()
    sb.placeholder = "Search"
    return sb
}()

fileprivate func setupNavBarAndSearchBar() {

    let navBar = navigationController?.navigationBar
    searchBar.delegate = self
    navigationController?.navigationBar.addSubview(searchBar)
    //Constraints already figured^^
}


func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {searchBar.setShowsCancelButton(true, animated: true)}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(true, animated: true)

}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.text = ""
}


override func viewDidLoad() {
    super.viewDidLoad()
    setupNavBarAndSearchBar()
    collectionView?.backgroundColor = .white
    collectionView?.register(UserProfileVideoCell.self, forCellWithReuseIdentifier: cellId)
  searchBar.addSubview(SearchUsersTv) **Compiles error "expected argument type UIView"**
}

这是我对该文件所拥有的内容" SearchUsersTv" :

class SearchUsersTv: UIView, UITableViewDelegate, UITableViewDataSource {
let cellId = "cellId"

var tableView = UITableView()

let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width

override init(frame: CGRect){
    super.init(frame: frame)

    setup()
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func setup() {

    self.backgroundColor = UIColor.black

    tableView = UITableView(frame: CGRect(x: 0, y: 0, width: screenWidth*0.5, height: screenHeight))
    tableView.layer.backgroundColor = UIColor.black.cgColor
    self.addSubview(tableView)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
    cell.backgroundColor = .magenta
    return cell
}
  

现在上面这个文件没有运行,因为它没有运行(它编译了一个   我尝试将其添加为第一个文件中的子视图时出错

1 个答案:

答案 0 :(得分:0)

将您的TableView alpha值设为" 0"首先在你的StoryBoard中。

简单地做到" 1.0"在你的

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {searchBar.setShowsCancelButton(true, animated: true)}
像这样

tableView.alpha = 1.0

希望这会有所帮助。它也解决了我的问题。