迅速让UITableView填满手机的整个视口。

问题描述 投票:0回答:1

平台

Swift 5, Xcode最新版本, iOS 13+。

问题:

我嵌入了一个 UITableView 变成 UIViewController,并使表格视图尽可能高。

    let screenRect = UIScreen.main.bounds
    let screenWidth = screenRect.size.width
    let screenHeight = screenRect.size.height
    

    let width  = self.view.frame.width
    let height = self.view.frame.height
    tableView.center = self.view.center
    tableView.frame.size.width  = width
    tableView.frame.size.height = screenHeight
        //= UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

这是很好的,当 UINavigationController 视图是可见的,但当导航控制器视图移开时,我看到tableview从视口顶部偏移了导航控制器视图的高度。在下图中,tableview及其单元格是白色的,而父UIViewController视图是黑色的。我们可以在这里看到父控制器。enter image description here

我试着偏移tablview,但没有达到预期的效果。

请注意,如果存在故事板解决方案,我希望避免使用它。请用代码说明一切,因为这个表格视图有其他的行为,我可能需要控制。

ios swift uitableview
1个回答
1
投票

关键是,如果你想让你的tableView布局自动更新,就要使用自动布局。要做到这一点,将你的tableView钉在safeArea上,如下所示。

    tableView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
    tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
    tableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
    tableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
    tableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
    ])
© www.soinside.com 2019 - 2024. All rights reserved.