ios - 当 UISearchController 处于事件状态时选择 TableView 中的单元格,不显示下一个 View ?

标签 ios swift swift2 uisearchcontroller

我制作了一个表格 View ,您可以在其中选择一个单元格,然后 View Controller 将执行到下一个 View 的segue,当您不使用搜索 Controller 时,它工作得非常好。 然后,当您使用searchcontroller时,它会按应有的方式过滤tableview,并在didSelectRowAtIndexPath中调用segue,并调用prepareForSegue。那么问题是它应该遵循的观点没有呈现出来?我可以看到连接到 View 的类中的代码正在运行,因此执行了segue,只是 View 没有跟随。我缺少什么

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 Losstandfound[949:2474251] 警告:尝试在已经呈现的内容上呈现

最佳答案

这是带有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)

}

}

关于ios - 当 UISearchController 处于事件状态时选择 TableView 中的单元格,不显示下一个 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819672/

相关文章:

ios - 提交以供Testflight(iOS)审查

ios - Xamarin.ios:应用程序中未加载图像资源目录

ios - OBJ-C : How to release object which is return from method?

ios - 如果我使用两个文本字段,如何设置键盘

swift - 使用快速自动布局滚动到 cellForRowAt Index 问题

ios - 使用未声明的类型 'Object'

xcode - 使用绑定(bind)的 NSTextFields 在初始化后不更新

ios - 如何修复 Realm for swift 2.0 安装报错?

ios - 如何在swift 3中仅在按钮的有界区域上获取触摸事件

ios - 针对不同目标的定位和非定位