我是一名新程序员,开始使用 xCode 还不到 3 周,所以这个问题对你来说可能看起来很愚蠢,但真的需要你的帮助。 这个问题不重复,因为之前的类似问题是关于重叠状态栏的,但我的情况是导航栏和选项卡栏消失了。 最初我在 View Controller 中设置了导航栏和选项卡栏。 但是,当我按照 Youtube 的代码设置 UITableView 后,它覆盖了所有内容,整个页面变成了 TableView ,如下所示: enter image description here
但我并不打算将表格覆盖到整个页面,而是留下导航栏和表格栏出现。我这样设置 View Controller : enter image description here
有什么可以帮我一个大忙,帮助我调整过来吗,谢谢! 代码是这样的:
class HomeViewController:UIViewController, UITableViewDelegate,
UITableViewDataSource {
var tableView:UITableView!
var posts = [
Post(id: "1", author: "Donald", text: "Ho"),
Post(id: "2", author: "Brian Yung", text: "Hi")
]
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.backgroundColor = UIColor.blue
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
view.addSubview(tableView)
var layoutGuide:UILayoutGuide!
if #available(iOS 11.0, *) {
layoutGuide = view.safeAreaLayoutGuide
} else {
// Fallback on earlier versions
layoutGuide = view.layoutMarginsGuide
}
tableView.contentInset.top = 50
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: 32).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
}
最佳答案
我也遇到过这个问题,并且永远无法弄清楚为什么会发生这种情况,即使 View 上的限制似乎是正确的......因此,在没有任何实际解决方案的情况下,我通过以下解决方法解决了它。看看它是否也对您有帮助。
解决方法的要点是:对 TableView 使用单独的 Controller ,并使用容器 View 将其嵌入“主” View
步骤:
- 在要添加 TableView 的 View 上,删除 TableView ,并在想要 TableView 的位置添加容器 View 。为其创建适当的约束(应从顶部和底部进行限制)
- 创建一个单独的 TableView Controller 。并为其创建一个新的 Controller 类。
UITableViewDelegate
和UITableViewDataSource
中的所有方法都应该从HomeViewController
移动到这个新 Controller - 创建从容器 View 到 TableView Controller 的嵌入转场
- 从
HomeViewController
中删除UITableViewDelegate、UITableViewDataSource
(它仅扩展UIViewController
)
即:
关于swift - UITableView 重叠一切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312475/