gpt4 book ai didi

ios - 如何自动调整显示搜索结果的tableView的大小?

转载 作者:行者123 更新时间:2023-11-30 11:09:52 26 4
gpt4 key购买 nike

这就是我添加 UITableView 的方式:

tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
tableView.rowHeight = 60.0
tableView.tableFooterView = UIView()
view.addSubview(tableView)

tableView.translatesAutoresizingMaskIntoConstraints = false

tableViewHeightAnchor = tableView.heightAnchor.constraint(equalToConstant: 0)
let constraints = [tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableViewHeightAnchor!]
NSLayoutConstraint.activate(constraints)

这部分尤其重要:

tableView.topAnchor.constraint(equalTo: view.topAnchor)

在我尝试将其连接到 UISearchController 的搜索栏的底部之前,但在这种情况下它崩溃了。

在我的

func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
tableView.reloadData()

UIView.animate(withDuration: 0.6) {
self.tableViewHeightAnchor.constant = self.tableView.contentSize.height
}
}

我正在调整高度 anchor 并将其设置为等于 tableView 的 contentSize。但我有一个问题:

当只有 1-2 行要显示时,我根本看不到我的 tableView!只有当我将 +200.0 添加到 contentSize 时才能看到它,但是这个解决方案非常糟糕并且难以控制,因为在这种情况下它无法正确显示。

我该如何解决这个问题?这是我第一次尝试用代码完成所有设计,有时真的很困惑。也许有人可以解释一下那里出了什么问题

最佳答案

您可以尝试使用这些约束,它会自动为您调整大小,直到高度达到与屏幕相同的高度,然后表格 View 将允许滚动。

NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true

关于ios - 如何自动调整显示搜索结果的tableView的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com