調整元件位置的五種方法

假設有個 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

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com