2017-02-27 37 views
0

你好我programmaticaly加入這樣問題與計劃增加的視圖

 let xPos = (self.view.frame.size.width - 200)/2 
     self.headerLabel = UILabel(frame: CGRect(x: xPos, y: 50.0, width: 200.0, height: 100.0)) 
     self.shopButton = UIButton(frame: CGRect(x: xPos, y: 150.0, width: 200.0, height: 40.0)) 
     self.createButton = UIButton(frame: CGRect(x: xPos, y: 230.0, width: 200.0, height: 40.0)) 
     self.orLabel = UILabel(frame: CGRect(x: xPos, y: 200.0, width: 200.0, height: 20.0)) 

問題的一些看法是,當我旋轉裝置,景觀模式,反之亦然我的看法是一致的左側。我怎樣才能防止它?

+0

你可以找到一些好的文檔/後有:http://stackoverflow.com/questions/27473810/how-to-change-layout-constraints-programmatically-on -display-rotation和https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html – Balanced

回答

0

在視圖中使用NSLayoutConstaint

其超強的看法添加約束例如

let horizontalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerX, relatedBy: .equal, toItem: view.superview, attribute: .centerX, multiplier: 1, constant: 1) 
     horizontalConstraint.isActive = true 

     let verticalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerY, relatedBy: .equal, toItem: view.superview, attribute: .centerY, multiplier: 1, constant: 1) 
     verticalConstraint.isActive = true 
0

如果可以的話我會在界面生成器中添加這些元素。然後您可以手動設置您的約束,這比以編程方式添加它們要容易得多。你看到這種行爲的原因是因爲你的元素沒有約束,所以當屏幕旋轉時它們不會改變方向。

請查看以下鏈接: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html

https://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2

0

如果你使用完全沒有故事板工作我推薦使用霓虹燈框架。 它可以幫助您設計整個視圖 - 也可以在其上放置按鈕,圖像... - 以編程方式。

請參見下面的Github上回購: https://github.com/mamaral/Neon