检查您的 segue 是如何设置的。你有一个从视图控制器连接到视图控制器的segue,还是从tableview连接到另一个视图控制器,或者你有两个segue?在这种情况下,您应该使用一个 segue,只是在不同的地方触发它
performSegue(withIdentifier: "yourSegueIdentifier")
看看我为你快速编写的这段代码:
你也可以从我的 github 上试试,然后和你的比较一下。搜索栏在这两种情况下都应该出现。
https://github.com/verebes1/SearchBarHelp
import UIKit
class MainViewController: UITableViewController {
var items = ["One", "Two", "Three"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: - Tableview methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showMembers", sender: self)
}
//MARK: - Segue setup
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
/* Put any preparation here if needed */
}
//MARK: Navbar Button action
@IBAction func searchBarButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "showMembers", sender: self)
}
}
和第二个viewController:
import UIKit
class SearchMembersController: UITableViewController, UISearchControllerDelegate {
var members = ["First", "Second", "Third", "Fourth"]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.title = NSLocalizedString("MEMBERS", comment: "")
let search = UISearchController(searchResultsController: nil)
self.definesPresentationContext = true
//search.searchResultsUpdater = self
search.dimsBackgroundDuringPresentation = false
navigationItem.searchController = search
navigationItem.hidesSearchBarWhenScrolling = false
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return members.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = members[indexPath.row]
return cell
}
}
从评论中引用您的代码:
leftButton.addTarget(self, action: #selector(Profile.searchMembers), for: .touchUpInside) self.settingsButton.customView = leftButton
这应该调用
performSegue(withIdentifier: "profileToMembers", sender: self)
而不是 Profile.searchMembers。可能会出错,您可以将其包装在 @objc 函数中,例如
@objc func segueToMembers(){
performSegue(withIdentifier: "profileToMembers", sender: self)
}
然后调用它
leftButton.addTarget(self, action: #selector(segueToMembers), for: .touchUpInside) self.settingsButton.customView = leftButton