在 UISearchController 处于活动状态时选择 tableview 中的单元格,不显示下一个视图?

Posted

技术标签:

【中文标题】在 UISearchController 处于活动状态时选择 tableview 中的单元格,不显示下一个视图?【英文标题】:selecting cell in tableview while UISearchController is active, doesnt present next view? 【发布时间】:2016-11-26 15:01:29 【问题描述】:

我制作了一个表格视图,您可以在其中选择一个单元格,然后视图控制器将执行下一个视图的 segue,当您不使用搜索控制器时,它可以正常工作。 然后,当您使用 searchcontroller 时,它会按应有的方式过滤 tableview,并在 didSelectRowAtIndexPath 中调用 segue,并调用 prepareForSegue。那么问题是没有提出它应该继续的观点?我可以看到连接到视图的类中的代码正在运行,所以进行了segue,只是视图没有跟随。我错过了什么

class CompanyListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating 

@IBOutlet weak var tableView: UITableView!

let objectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

var activityIndicatorView: SWActivityIndicatorView!

var resultSearchController: UISearchController!

var allCompanies: [Company] = []
var filteredCompanies = [Company]()

override func viewDidLoad() 
    super.viewDidLoad()


    // set delegates
    tableView.delegate = self
    tableView.dataSource = self

    configureSearchController()


    // initialize activity indicator view
    self.activityIndicatorView = SWActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    activityIndicatorView.hidesWhenStopped = true
    activityIndicatorView.color = UIColor.lightGrayColor()
    self.view.addSubview(activityIndicatorView)
    self.activityIndicatorView.center = self.view.center
    activityIndicatorView.startAnimating()

    // fetch all records from backend
    fetchAllRecords((errors: [NSError]?) -> Void in if errors != nil print(errors))



func configureSearchController() 
    // Initialize and perform a minimum configuration to the search controller.
    // Search Bar
    self.resultSearchController = UISearchController(searchResultsController: nil)
    self.resultSearchController?.searchBar.autocapitalizationType = .None
    self.tableView.tableHeaderView = self.resultSearchController?.searchBar
    resultSearchController?.dimsBackgroundDuringPresentation = false
    self.resultSearchController?.searchResultsUpdater = self
    definesPresentationContext = true






// search delegate method
func updateSearchResultsForSearchController(searchController: UISearchController) 

        self.filterContentForSearchText(searchController.searchBar.text!)




// Filter method, which filters by companyName, and reloads tableview
func filterContentForSearchText(searchText: String, scope: String = "All") 
    filteredCompanies = allCompanies.filter  company in
        return company._companyName!.lowercaseString.containsString(searchText.lowercaseString)
    

    tableView.reloadData()


// fetch all records from backend
func fetchAllRecords(completionHandler: (errors: [NSError]?) -> Void) 

    let scanExpression = AWSDynamoDBScanExpression()

    objectMapper.scan(Company.self, expression: scanExpression)  (response: AWSDynamoDBPaginatedOutput?, error: NSError?) in
        dispatch_async(dispatch_get_main_queue(), 
            // if error
            if let error = error 
                completionHandler(errors: [error]);
            
                //if success
            else 
                self.allCompanies = response!.items as! [Company]
                self.tableView.reloadData()
                self.activityIndicatorView.stopAnimating()

            
        )
    




func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

    if resultSearchController.active && resultSearchController.searchBar.text != "" 
        return filteredCompanies.count
    

    return allCompanies.count




func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

    // create a new cell if needed or reuse an old one
    let cell:CompanyListTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("companyCell") as! CompanyListTableViewCell

    // set the text from the data model
    let company:Company?

    if resultSearchController.active && resultSearchController.searchBar.text != "" 
        company = self.filteredCompanies[indexPath.row]


     else 
        company = self.allCompanies[indexPath.row]
    

    cell.titleLabel.text = company!._companyName
    cell.imageview?.image = UIImage(named: "placeholder")

    return cell




func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 

self.performSegueWithIdentifier("segueToProfile", sender: self)




// send selected company with segue to profile
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 

    if(segue.identifier == "segueToProfile")
        let indexPath = tableView.indexPathForSelectedRow

        //tableView.deselectRowAtIndexPath(indexPath!, animated: true)

        let selectedRow = indexPath!.row
        let profileVC = segue.destinationViewController as! ProfileViewController

        if resultSearchController.active

            print(filteredCompanies[selectedRow])
            profileVC.company = filteredCompanies[selectedRow]

         else 

            profileVC.company = allCompanies[selectedRow]

        
    


控制台这样说,但我不知道这是否与此有关?

2016-11-26 15:54:07.300 Lostandfound[949:2474251] 警告:尝试展示已经展示的对象

【问题讨论】:

这是完整的控制台消息:2016-11-26 15:54:07.300 Lostandfound[949:2474251] 警告:尝试在 > 已经在呈现 【参考方案1】:

这里是带有 SearchBar 控件的 TableView 示例。您应该删除 didSelectRowAtIndexPath 方法并使用 prepareForSegue 方法来确定 TableView 中的选定行。像这样...

例子:

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate


@IBOutlet weak var SerchBar: UISearchBar!
@IBOutlet weak var TableView: UITableView!


var searchActive : Bool = false
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []

override func viewDidLoad()

    super.viewDidLoad()



private func numberOfSectionsInTableView(tableView: UITableView) -> Int

    return 1

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    if(searchActive)
    
        return filtered.count
    
    return data.count;


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

    let cell = self.TableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
    if(searchActive)
    
        cell.Label.text = filtered[indexPath.row]
    
    else
    
        cell.Label.text = data[indexPath.row]
    

    return cell


override func prepare(for segue: UIStoryboardSegue, sender: Any!)

    if let cell = sender as? TableViewCell
    
        let i = TableView.indexPath(for: cell)!.row
        if segue.identifier == "segue1"
        
            if(searchActive)
            
                let name1 = segue.destination as! SecondView
                name1.str = self.filtered[i]
            
            else
            
                let name1 = segue.destination as! SecondView
                name1.str = self.data[i]

            
        
    


func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)

    filtered = data.filter( (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: .caseInsensitive)
        return range.location != NSNotFound
    )
    if(filtered.count == 0)
    
        searchActive = false;
    
    else
    
        searchActive = true;
    
    self.TableView.reloadData()


func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)

    searchActive = true;


func searchBarTextDidEndEditing(_ searchBar: UISearchBar)

    searchActive = false;


func searchBarCancelButtonClicked(_ searchBar: UISearchBar)

    searchActive = false;


func searchBarSearchButtonClicked(_ searchBar: UISearchBar)

    searchActive = false;


override func didReceiveMemoryWarning()

    super.didReceiveMemoryWarning()


您的 SecondView 课程是:

import UIKit

class SecondView: UIViewController

@IBOutlet weak var label: UILabel!
var str:String!

override func viewDidLoad()

    super.viewDidLoad()
    self.label.text = str


override func didReceiveMemoryWarning()

    super.didReceiveMemoryWarning()



你的 TableViewCell 是:

import UIKit

class TableViewCell: UITableViewCell

@IBOutlet weak var Label: UILabel!
override func awakeFromNib()

    super.awakeFromNib()


override func setSelected(_ selected: Bool, animated: Bool)

    super.setSelected(selected, animated: animated)




【讨论】:

以上是关于在 UISearchController 处于活动状态时选择 tableview 中的单元格,不显示下一个视图?的主要内容,如果未能解决你的问题,请参考以下文章

当 UISearchController 的 searchBar 处于活动状态时,点击 UITableView 索引 (A...Z)

当 UISearchController 处于活动状态并选择新选项卡时,UITableView 消失

当 UISearchController 处于活动状态时,iOS 9 searchBar 从表头视图中消失

带有大标题的 UISearchController 在选项卡栏中崩溃,“只有一个带有顶部边界的调色板可以在过渡之外处于活动状态”

UISearchController 搜索栏在活动时与第一个单元格重叠

关闭并滑动以关闭搜索控制器处于活动状态的问题