I have a tableView with textFields in it and on portrait I want the widthContstraint 550 and in landscape 1050. I was able to detect the rotation and change the value, but the tableView does not update when rotating, although the amount is changing correctly every time I rotate. So I guess I need to update the new value somewhere?
This is my code:
var widthConstraint: CGFloat? = nil
// Override view did load function
override func viewDidLoad() {
super.viewDidLoad()
setupContent()
// Rotation detection
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func rotated() {
// Change the width when rotating
widthConstraint = DeviceHelper.isIpadAndLandscape() ? 1050 : 550
// Update the view again after rotating
tableView?.updateConstraints()
}
// Private func setup content
private func setupContent() {
self.setupTableView()
}
// Private setup table view
private func setupTableView() {
self.tableView?.dataSource = self
self.tableView?.delegate = self
if let tableView = self.tableView {
self.view.addSubview(tableView)
}
self.tableView?.anchor(top: self.view.safeAreaLayoutGuide.topAnchor, leading: nil, bottom: self.view.safeAreaLayoutGuide.bottomAnchor, trailing: nil, padding: UIEdgeInsets(top: 16, left: 0, bottom: 8, right: 0))
self.leadingAnchorConstraint = self.tableView?.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor)
self.trailingAnchorConstraint = self.tableView?.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor)
self.widthAnchorConstraint = self.tableView?.widthAnchor.constraint(equalToConstant: widthConstraint ?? 550)
self.centerXAnchorConstraint = self.tableView?.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor)
self.setupConstraints()
}