添加UISearchController后,UITableView可以滚动得太远

时间:2018-04-14 08:13:05

标签: ios swift uitableview uisearchbar

使用以下代码将UISearchController添加到UITableView后。

lazy var searchCardController: SearchCardController = {
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SearchCard") as? SearchCardController
}()!

lazy var searchController: UISearchController = {
    return UISearchController(searchResultsController: searchCardController)
}()

//Core Data
lazy var stack: CoreDataStack = {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    return delegate.stack
}()

lazy var dataSource: CardCategoryDataSource = {
    // Create a fetchrequest
    let fr = NSFetchRequest<NSFetchRequestResult>(entityName: "CD_CardCategory")
    fr.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    // Create the FetchedResultsController
    fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil)

    return CardCategoryDataSource(fetchedResultsController: fetchedResultsController!)
}()


override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = dataSource

    setupSearchBar()
}

func setupSearchBar() {

    searchController.searchBar.delegate = searchCardController
    searchController.searchResultsUpdater = searchCardController
    searchController.dimsBackgroundDuringPresentation = true
    searchController.searchBar.barTintColor = UIColor.black
    searchController.searchBar.tintColor = UIColor.white

    searchCardController.searchController = searchController

    definesPresentationContext = true

    self.tableView.tableHeaderView = searchController.searchBar

}

UITableView可以向上滚动太远,这有点奇怪,如下面的屏幕截图所示。 enter image description here

据说表视图应该像下面的屏幕截图一样。 enter image description here

非常感谢任何帮助。

更新: 添加GIF以更好地解释问题。 enter image description here

1 个答案:

答案 0 :(得分:0)

在我将estimatedRowHeight定义为我想要的确切行高后,问题得到解决,如viewDidLoad中所示。

self.tableView.estimatedRowHeight = 150

特别感谢@Harman给我的想法。