調整元件位置的五種方法
Published in
Oct 16, 2018
假設有個 outlet 連到畫面上的 image view。
一. 修改 origin
imageView.frame.origin = CGPoint(x: 30, y: 30)
只修改 origin 的 x。
imageView.frame.origin.x = 30
二. 修改 center
imageView.center = CGPoint(x: 30, y: 30)
只修改 center 的 x。
imageView.center.x = 30
三. 修改 transform
讓元件從原本的 (x, y) 偏移 (translationX,translationY)。比方以下例子,當元件的 origin 本來在 (20, 50),設定 transform 後,origin 將變成在 (50,70)。
imageView.transform = CGAffineTransform(translationX: 30, y: 20)
四. 呼叫 offsetBy(dx:dy:)
讓元件從原本的 (x, y) 偏移 (translationX,translationY)。比方以下例子,當元件的 origin 本來在 (20, 50),offsetBy(dx: 10, dy: 20) 後,origin 將變成在 (30,70)。
imageView.frame = imageView.frame.offsetBy(dx: 10, dy: 20)
五. 修改 Auto Layout constraint 的 constant
假設有個 outlet 連到 image view 的 top constraint。
topSpaceConstraint.constant = 30