Last active
March 27, 2017 14:50
-
-
Save denkeni/c641625b20884c891221a87350175953 to your computer and use it in GitHub Desktop.
Auto Layout Programmatically 1-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
subviewA.translatesAutoresizingMaskIntoConstraints = false // 這是純程式碼寫 Auto Layout 的大雷:必須設定這一行! | |
view.addSubview(subviewA) | |
var constraints = [NSLayoutConstraint]() | |
constraints.append(NSLayoutConstraint(item: subviewA, attribute: .centerX, relatedBy: .equal, | |
toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0)) | |
// subviewA.centerX = 1.0 * view.centerX + 0 即 subviewA.centerX = view.centerX | |
constraints.append(NSLayoutConstraint(item: subviewA, attribute: .centerY, relatedBy: .equal, | |
toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0)) | |
// subviewA.centerY = 1.0 * view.centerY + 0 即 subviewA.centerY = view.centerY | |
constraints.append(NSLayoutConstraint(item: subviewA, attribute: .width, relatedBy: .equal, | |
toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 200)) | |
// subviewA.width = 0 * nil + 200.0 即 subviewA.width = 200 | |
constraints.append(NSLayoutConstraint(item: subviewA, attribute: .height, relatedBy: .equal, | |
toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 100)) | |
// subviewA.centerX = 0 * nil + 100.0 即 subviewA.height = 100 | |
NSLayoutConstraint.activate(constraints) // 這些 constraint 必須 activate 才會啟用 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment