2016-09-13 36 views
1

我有一個在我的視圖控制器編程方式創建一個表視圖:處理UITableView的旋轉而自動佈局

/// Configures the table view used to display systems. 
private func configureTableView() { 
    guard let navigationBarHeight = navigationController?.navigationBar.frame.height else { fatalError("Invalid height for navigation bar") } 
    let statusBarHeight = UIApplication.shared.statusBarFrame.height 
    let totalHeight = navigationBarHeight + statusBarHeight 
    view.insertSubview(tableView, aboveSubview: noSystemsLabel) 
    tableView.translatesAutoresizingMaskIntoConstraints = false 
    tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: totalHeight).isActive = true 
    tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true 
    tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true 
    tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true 
} 

一切看起來好這裏:

enter image description here

然後,我轉動我的設備並且分隔符不會跨越表視圖的寬度另外,當我滾動表視圖時,頂部單元格會在到達導航欄之前被切斷:

enter image description here

旋轉回肖像後,表視圖似乎更高,從而導致頂部細胞會被裁切:

enter image description here

我一直在使用這下面的方法有不同的解決方案嘗試,如重新配置coordinator的動畫內的限制,但我只是無法弄清楚如何得到它正常工作:

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

我試圖找出如何使用這種方法,但我想我不是很瞭解它。

如何使用我的表格視圖配置自動佈局,使其在旋轉設備時尺寸和位置適當?

肖像:

enter image description here

景觀:

更新

針對Aerows答案,我仍然實現所提出的解決方案後,越來越怪異結果enter image description here

更新 - 工作液

繼Aerow的建議下,我用topLayoutGuide.bottomAnchor,這解決了我的問題。

回答

1

嘗試將tableViewtop constraint設置爲viewtopLayoutGuide

tableView.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true 

的原因是constant您在top constraint設置是正確的肖像模式,但在風景模式狀態欄的高度是不一樣的(的0.f代替20.f) 。

如果您的示例中的navigationBar是自動處理的,那麼topLayoutGuide將始終位於可見view的頂部。

至於cells,這可能是由於您的tableView如何處理separatorsinsets。嘗試將tableViewcell的背景顏色設置爲固體,並查看是否擴展了整個view

下面是我運行驗證此代碼的完整代碼。

override func viewDidLoad() { 
    super.viewDidLoad() 

    let tableView = UITableView(frame: view.frame, style: .Plain) 

    tableView.translatesAutoresizingMaskIntoConstraints = false; 
    tableView.backgroundColor = UIColor.blueColor() // For visualisation 
    self.view.addSubview(tableView) 

    tableView.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true 
    tableView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true 
    tableView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true 
    tableView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true 
} 
+0

我實現了您的解決方案,但這會導致表視圖始終處於導航欄下。 –

+0

您是否還手動添加了「導航欄」,還是繼承自「navigationController」? – Aerows

+0

'navigationBar'繼承自Interface Builder中的'UINavigationController'。 –