iOS Building GUI

正文

XYWH

開一個iOS 的 project
然後在default的VC中的viewdidload中加入

1
2
3
4
5
6
7
8
9
10
11
12
13
import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let XYWDView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
XYWDView.backgroundColor = .red
self.view.addSubview(XYWDView)
}

}

alt text

Storyboard + Autolayout

alt text

alt text

XIB + Autolayout

首先在AppDelegate didFinishLaunchingWithOptions 中加入

1
2
3
4
5
6
7
8
9
10
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window?.backgroundColor = UIColor.white
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: ViewController())

return true
}

然後在刪去 Main Interface 中的Main SB

加入一個Xib

加入Class ViewController

把 Outlet View 連上

最後加入 NSLayoutConstraint

alt text

alt text

alt text

alt text

alt text

Pure Code + Autolayout

首先跟上面一樣在AppDelegate didFinishLaunchingWithOptions 中加入一段Code

然後在刪去 Main Interface 中的Main SB

最後在default的VC中的viewdidload中加入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = .white

let colorView = UIView()
colorView.backgroundColor = .red
colorView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(colorView)

self.view.addConstraint(NSLayoutConstraint(item: colorView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
self.view.addConstraint(NSLayoutConstraint(item: colorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
self.view.addConstraint(NSLayoutConstraint(item: colorView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 100))
self.view.addConstraint(NSLayoutConstraint(item: colorView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 100))
}

alt text