UITableViewCell 列宽根据屏幕方向变化 IOS Swift

UITableViewCell column width change based on screen orientation IOS Swift

我需要在我正在开发的其中一个应用程序中制作类似于 table 的结构。我正在使用 UITableView 创建此 table 并且我需要根据屏幕方向更改 table 列宽。我已经为列宽设置了限制条件,我将使用 viewDidLoad() 中的屏幕宽度为这些值分配值。

但是,我不知道如何在屏幕方向改变时重新对齐这些约束。我发现当方向改变时 viewWillTransition() 将被调用 & 我重新计算了其中的约束 & 为 table 视图调用了 setNeedsLayout() 。但是,当屏幕方向更改时,我无法使 table 视图重置 table 列宽。我是 IOS 平台的新手,非常感谢任何帮助。

HDR_parName/HDR_parValue/HDR_minValue/HDR_maxValue

Para1/value1/minvalue1/maxvalue1

Para2/value2/minvalue2/maxvalue2

很简单的解决方法,你的做法是错误的。 考虑您想要全宽作为行宽。

您不必为单元格宽度设置任何约束,而是为您的表格视图设置尾随约束。它会处理所有问题。

如果您仍然遇到类似的问题,请尝试

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    self.view.layoutIfNeeded()
}

如果您仍然遇到此问题,请告诉我。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    let animationHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called several times during rotation, 
        // so if you want your tableView change more smooth reload it here too. 
        self?.tableView.reloadData()
    }

    let completionHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called when rotation will be completed
        self?.tableView.reloadData()
    }

    coordinator.animateAlongsideTransition(animationHandler, completion: completionHandler)

}

然后将调用tableView 数据源和委托方法,您可以在其中根据tableView 框架大小设置元素大小。

Swift 4

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let animationHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called several times during rotation,
        // so if you want your tableView change more smooth reload it here too.
        self?.yourTable.reloadData()
    }

    let completionHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { [weak self] (context) in
        // This block will be called when rotation will be completed
        self?.yourTable.reloadData()
    }

    coordinator.animate(alongsideTransition: animationHandler, completion: completionHandler)

}