2017-02-15 55 views
0

我使用的Xcode 8.2,斯威夫特3iOS屏幕幾何圖形的佈局如何工作?

我想以編程方式創建UIViewController一些文本(和將來,一些圖形)屏幕上的內容。通常情況下,這與Storyboard很容易做到,但由於這個ViewController是以編程方式創建的,所以我必須這樣工作。

這是到目前爲止我的代碼:

let detailViewController = UIViewController() 
detailViewController.view.backgroundColor = UIColor.white 

let screenSize = UIScreen.main.bounds 
let screenWidth = screenSize.width 
let screenHeight = screenSize.height 

let titleLabel = UILabel(frame: CGRect(x: 20, y: 20, width: screenWidth, height: 20)) 
titleLabel.center = CGPoint(x: screenWidth/2, y: 100) 
titleLabel.backgroundColor = UIColor.red 
titleLabel.textAlignment = .center 
titleLabel.text = "Scan Results" 
titleLabel.font = UIFont.boldSystemFont(ofSize: 14) 

let myField: UITextView = UITextView (frame: CGRect(x: 50, y: 50, width: screenWidth, height: 300)) 
myField.center = CGPoint(x: screenWidth/2, y: 250) 
myField.backgroundColor = UIColor.green 

myField.text = <really long string here> 

detailViewController.view.addSubview(titleLabel) 
detailViewController.view.addSubview(myField) 

這是我所看到的:

![enter image description here

這引發了很多問題要問我,因爲我想了解如何佈局的作品,但似乎無法找到任何對我有意義的幫助。

我的screenWidthscreenHeight分別是375和667。我正在使用iPhone 7.我已將titleLabel定位在中心位置,但位於y: 100。但是,如果標籤的最終結果看起來不像1/6,因爲屏幕的高度爲667.

那麼文本定位究竟如何工作?我知道左上角是原點,但這就是它。

此外,我開始我的文本字段在x: 50, y: 50寬度爲screenWidth。那麼爲什麼文本溢出頁面而不是環繞?

非常感謝您的幫助。

+0

更改您的標籤背景的顏色,以便您可以看到發生了什麼更好。如果標籤佔據了整個空白空間,那麼這有些是正確的行爲,文本始終在標籤的垂直中心,並且可能只設置爲單行。 – Fonix

+0

哦,等等,爲什麼myField是' UITextField'?你的意思是使用'UITextView'嗎? – Fonix

+0

好眼睛。讓我進行這些更改並更新我的問題。 – noblerare

回答

1

我認爲如果你設置不同視圖的框架(通過構造函數或其他),不要設置.center以及它會影響它的x和y位置,因此爲什麼他們的位置是關閉的

1

你必須以編程方式添加約束,例如:

NSLayoutConstraint(item: myField, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: detailViewController, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1.0, constant: 20.0).isActive = true 

myField.widthAnchor.constraint(equalToConstant: 200).isActive = true 
myField.heightAnchor.constraint(equalToConstant: 100).isActive = true 

檢查這個答案詳細信息:https://stackoverflow.com/a/36263784/4077559。我認爲這是你正在尋找的