NSLayoutConstraint Programming

Henry Huang
Dec 31, 2021

--

在iOS裡用storyboard建立UI和拉layoutConstraint是很方便、易學及快速的,但純程式碼建立UI也是很多人會選擇的方式,畢竟Xcode的storyboard速度實在有點慢。

用程式碼設定LayoutConstraint,要建立這樣的畫面

這樣簡單的畫面就要這麼多行

所以可以幫UIView建立一個Extention,來設定LayoutConstraint

extension UIView {  func setConstraint(topA: NSLayoutYAxisAnchor, topConstraint: CGFloat?, leadingA: NSLayoutXAxisAnchor, leadingConstraint: CGFloat?, bottomA:NSLayoutYAxisAnchor, bottomConstraint: CGFloat?, trailingA: NSLayoutXAxisAnchor, trailingConstraint: CGFloat?) {    self.translatesAutoresizingMaskIntoConstraints = false    if topConstraint != nil {      self.topAnchor.constraint(equalTo: topA, constant:     topConstraint!).isActive = true    }    if leadingConstraint != nil {      self.leadingAnchor.constraint(equalTo: leadingA, constant: leadingConstraint!).isActive = true    }    if bottomConstraint != nil {      self.bottomAnchor.constraint(equalTo: bottomA, constant: -bottomConstraint!).isActive = true    }    if trailingConstraint != nil {      self.trailingAnchor.constraint(equalTo: trailingA, constant: - trailingConstraint!).isActive = true    }  }}

這樣要在建立一個View設定LayoutConstraint就輕鬆多囉!

--

--

Henry Huang
Henry Huang

Written by Henry Huang

大學讀企管/退伍後在業務圈打滾6年後突然有一天決定投入完全沒接觸過的程式設計/目前為一位iOS Developer/熱愛NBA/dafu1231@gmail.com

No responses yet