Auto Layout 自適應
宣告資料
var l1 = UILabel()
var l2 = UILabel()
var l3 = UILabel()
viewDidLoad
建立l1, 設定位置
l1.text = "1st" l1.backgroundColor = .white l1.translatesAutoresizingMaskIntoConstraints = false view.addSubview(l1) // l1 頂端 = view 頂端 + 100 let l1top = NSLayoutConstraint(item: l1, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 50) // l1 x軸中心 = view x軸中心 let l1centerx = NSLayoutConstraint(item: l1, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0) view.addConstraints([l1top, l1centerx])
建立l2, 對應l1, view 位置
l2.text = "2nd" l2.backgroundColor = .white l2.textAlignment = .center l2.translatesAutoresizingMaskIntoConstraints = false l2.layer.cornerRadius = 25 l2.layer.masksToBounds = true view.addSubview(l2) // l2 寬度 = 50 let l2width = NSLayoutConstraint(item: l2, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50) // l2 高度 = 50 let l2height = NSLayoutConstraint(item: l2, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50) // l2 頂端 = l1 底部 + 100 let l2top = NSLayoutConstraint(item: l2, attribute: .top, relatedBy: .equal, toItem: l1, attribute: .bottom, multiplier: 1, constant: 100) // l2 右方 = view x軸中心 − 100 let l2trailing = NSLayoutConstraint(item: l2, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: -100) view.addConstraints([l2width, l2height, l2top, l2trailing])
建立l3, 對應l2, view 位置
l3.text = "3rd" l3.textAlignment = .center l3.backgroundColor = .white l3.translatesAutoresizingMaskIntoConstraints = false l3.layer.shadowOpacity = 10 l3.layer.shadowColor = UIColor.black.cgColor l3.layer.shadowOffset = CGSize(width: 2, height: 2) view.addSubview(l3) // l3 寬度 = 50 let l3width = NSLayoutConstraint(item: l3, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50) // l3 高度 = 50 let l3height = NSLayoutConstraint(item: l3, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50) // l3 y軸中心 = l2 y軸中心 let l3centery = NSLayoutConstraint(item: l3, attribute: .centerY, relatedBy: .equal, toItem: l2, attribute: .centerY, multiplier: 1, constant: 0) // l3 左方 = view x軸中心 + 100 let l3leading = NSLayoutConstraint(item: l3, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 100) view.addConstraints([l3width, l3height, l3centery, l3leading])
下載完整範例 OneDrive