2016-11-26 51 views
0

我已经做了一个tableview,你可以选择一个单元格,然后viewcontroller会执行一个segue到下一个视图,当你不使用searchcontroller的时候,它工作得很好。 然后,当您使用searchcontroller时,它会按照它应该过滤tableview,并且在didSelectRowAtIndexPath中调用segue,并调用prepareForSegue。那么问题是它应该延续的视图不会被呈现?我可以看到连接到视图的类中的代码正在运行,所以执行了segue,它只是不遵循的视图。我缺少什么当UISearchController处于活动状态时在tableview中选择单元格时,不存在下一个视图?

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]警告:尝试以呈现在其上呈现已经

+0

这是完整控制台消息: 2016年11月26日15:54:07.300 Lostandfound [949:2474251]警告:尝试以呈现它已经呈现 kMose

回答

0

在这里被TableView中的与搜索栏control.You的例子应该删除didSelectRowAtIndexPath方法的方法和使用prepareForSegue方法确定TableView.Like这个选定的行...

例子:

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) 

} 

} 
相关问题