iOS布局相關知識梳理

image.png

iOS 布局機制

iOS 布局機制大概分這么幾個層次:

  • frame layout
  • autoresizing
  • auto layout
frame layout

即通過設置view的frame/bounds屬性值進而控制view相對于superview的位置和大??;
設置view的frame/bounds一般都是根據屏幕大小計算的,最常見的做法是將屏幕寬高定義為常量,還有就是創建UIView分類實現x,y,width,height等方法直接獲取view的寬高等;

let kScreenWidth = UIScreen.main.bounds.width
let kScreenHeight = UIScreen.main.bounds.height
extension UIView {
    public var width:CGFloat {
        get {
            return self.frame.width
        }set {
            var rect = self.frame
            rect.size.width = newValue
            self.frame = rect
        }
    }
}
autoresizing

基于autoresizing機制,能夠讓subview和superview維持一定的布局關系,當superview 的size改變時,subview也會 做出相應的調整;一般用于各種屏幕的適配以及橫豎屏的適配;
可以通過UIView的屬性autoresizingMask實現autoresizing:

    public struct AutoresizingMask : OptionSet {
        public init(rawValue: UInt)

        // 自動調整view與父視圖左邊距,以保證右邊距不變
        public static var flexibleLeftMargin: UIView.AutoresizingMask { get }
        // 自動調整view的寬度,保證左邊距和右邊距不變
        public static var flexibleWidth: UIView.AutoresizingMask { get }
        // 自動調整view與父視圖右邊距,以保證左邊距不變
        public static var flexibleRightMargin: UIView.AutoresizingMask { get }
        // 自動調整view與父視圖上邊距,以保證下邊距不變
        public static var flexibleTopMargin: UIView.AutoresizingMask { get }
        // 自動調整view的高度,以保證上邊距和下邊距不變
        public static var flexibleHeight: UIView.AutoresizingMask { get }
        // 自動調整view與父視圖的下邊距,以保證上邊距不變
        public static var flexibleBottomMargin: UIView.AutoresizingMask { get }
    }

橫豎屏適配的場景:

let view = UIView.init()
view.backgroundColor = UIColor.blue
view.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 200)
view.autoresizingMask = .flexibleWidth
self.view.addSubview(view)
ddd

autoresizingMask也可以設置多種:

view.autoresizingMask = [.flexibleWidth,.flexibleBottomMargin]

作用是:view的寬度按照父視圖的寬度比例進行縮放,距離父視圖頂部距離不變

auto layout

基于 autoresizing 機制,我們只能處理subview和superview的關系,而無法處理兄弟view 之間的關系,也無法反向處理,如讓superview依據subview的大小進行調整。而auto layout能很好的處理各種關系,它是一種基于約束的布局系統,可以根據元素上設置的約束自動調整元素的位置和大小。

autoresizing 和 auto layout 只能二選一,若要對某個view 采用auto layout布局,則需要設置其translatesAutoresizingMaskIntoConstraints屬性值為false。

代碼實現auto layout大致有三種方式:

  • UIKit框架提供的自動布局的NSLayoutConstraint方法
/**
 設置約束
 @param view1 指定需要添加約束的視圖一
 @param attr1 指定視圖一需要約束的屬性
 @param relation 指定視圖一和視圖二添加約束的關系
 @param view2 指定視圖一依賴關系的視圖二;attr1為height,width時可為nil
 @param attr2 指定視圖一所依賴的視圖二的屬性,若view2=nil,該屬性設置notAnAttribute
 @param multiplier 視圖一相對視圖二約束系數   
 @param c 視圖一相對視圖二約束偏移量 
 @return 返回生成的約束對象
 */
public convenience init(item view1: Any, attribute attr1: NSLayoutConstraint.Attribute, relatedBy relation: NSLayoutConstraint.Relation, toItem view2: Any?, attribute attr2: NSLayoutConstraint.Attribute, multiplier: CGFloat, constant c: CGFloat)
let view = UIView.init()
view.backgroundColor = UIColor.blue
self.view.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let constraint1 = NSLayoutConstraint.init(item: view, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
let constraint2 = NSLayoutConstraint.init(item: view, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0)
let constraint3 = NSLayoutConstraint.init(item: view, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)
let constraint4 = NSLayoutConstraint.init(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200)
self.view.addConstraints([constraint1,constraint2,constraint3,constraint4])
  • VFL(Visual Format Language)
    VFL是一種聲明性語言,VFL允許你通過一個格式化后的代碼字符串迅速定義視圖的自動布局約束。
    VFL語法
/**
 VFL設置約束
 @param format VFL語句,如:“H:|-0-[view]-0-|”
 @param opts 描述VFL中的所有對象的屬性和布局的方向,默認directionLeadingToTrailing
 @param metrics VFL語句中使用到的變量,key值為VFL語句中的變量名
 @param views VFL語句中使用到的視圖
 */
open class func constraints(withVisualFormat format: String, options opts: NSLayoutConstraint.FormatOptions = [], metrics: [String : Any]?, views: [String : Any]) -> [NSLayoutConstraint]
let view = UIView.init()
view.backgroundColor = UIColor.blue
self.view.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false

// H:水平方向,V:垂直方向;|父視圖,
let constraint1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view":view])
let constraint2 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view(height)]", options: .directionLeadingToTrailing, metrics: ["height" : 200], views: ["view":view])
self.view.addConstraints(constraint1)
self.view.addConstraints(constraint2)
auto layout反向處理

auto layout能反向處理,如讓superview依據subview的大小進行調整:

let superview = UIView.init()
superview.backgroundColor = UIColor.orange
self.view.addSubview(superview)

let subview1 = UIView.init()
subview1.backgroundColor = UIColor.red
superview.addSubview(subview1)

let subview2 = UIView.init()
subview2.backgroundColor = UIColor.blue
superview.addSubview(subview2)

superview.snp.makeConstraints { (make) in
    make.leading.equalTo(10)
    make.top.equalTo(20)
    make.width.equalTo(100)
}

subview1.snp.makeConstraints { (make) in
    make.leading.top.equalToSuperview().offset(10)
    make.trailing.equalToSuperview().offset(-10)
    make.height.equalTo(100)
}

subview2.snp.makeConstraints { (make) in
    make.leading.trailing.height.equalTo(subview1)
    make.top.equalTo(subview1.snp.bottom).offset(10)
    make.bottom.equalToSuperview().offset(-10)
}
mm
auto layout獲取布局前size

在布局完成前,我們不能通過view.frame.size獲取view的 size(這時size為{0,0})。有時候,我們需要在auto layout system對view完成布局前就知道它的size,例如UITableViewCell需要回調tableView:heightForRowAtIndexPath:返回每行的高度,這時可以使用systemLayoutSizeFittingSize:方法實現:

self.view.addSubview(label)
label.snp.makeConstraints { (make) in
    make.leading.top.equalToSuperview().offset(20)
}
let size = label.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

自適應布局

自適應布局,即控件size由其content動態決定;具有content的控件如UILabel、UIButton等能直接計算出content(如UILabel的text、UIButton的title,UIImageView的image)的大小。
auto layout system在布局時,如果不知道該為view分配多大的size,就會回調view的intrinsicContentSize方法,該方法會給auto layout system一個合適的size,system根據此 size對view的大小進行設置。對于UILabel這類控件,intrinsicContentSize返回的是根據其content計算出的size。有些view不包含content,例如UIView,這種 view 被認為has no intrinsic size,它們的intrinsicContentSize返回的值是(-1,-1);
UIScrollView及其子類,雖然也包含 content,由于它們是滾動的,auto layout system在對這類view進行布局時總會存在一些未定因素,這些 view的intrinsicContentSize也直接返回(-1,-1);
因此,對于能返回正確的intrinsicContentSize的view,auto layout可以使view自適應:

let label = UILabel.init()
label.backgroundColor = UIColor.orange
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "chang a chang"
self.view.addSubview(label)
let constraint1 = NSLayoutConstraint.init(item: label, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 10)
let constraint2 = NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
self.view.addConstraints([constraint1,constraint2])
zz

對于多行文字的UILabel,需要指定Label的寬度才能自適應:
指定Label的寬度的兩種方式:設置preferredMaxLayoutWidth 屬性:

label.numberOfLines = 0
label.text = "chang a chang chang a chang chang a chang chang a chang chang a chang"
self.view.addSubview(label)
let constraint1 = NSLayoutConstraint.init(item: label, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 10)
let constraint2 = NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
self.view.addConstraints([constraint1,constraint2])
label.preferredMaxLayoutWidth = 100

設置label寬度約束:

let constraint1 = NSLayoutConstraint.init(item: label, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 10)
let constraint2 = NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
let constraint3 = NSLayoutConstraint.init(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
self.view.addConstraints([constraint1,constraint2,constraint3])
rrr

對于frame layout的控件,可以調用sizeToFitsizeThatFits方法做到自適應size:

// 單行
label.x = 10
label.y = 20
label.text = "chang a chang"
label.sizeToFit()
self.view.addSubview(label)
// 多行
label.numberOfLines = 0
label.text = "chang a chang chang a chang chang a chang chang a chang chang a chang"
let size = label.sizeThatFits(CGSize(width: 100, height: 0))
label.frame = CGRect(origin: CGPoint(x: 10, y: 20), size: size)
self.view.addSubview(label)

對于intrinsicContentSize不能返回正常size的view,同樣也可以使用sizeToFitsizeThatFits方法手動做到自適應:

let textview = UITextView.init()
textview.backgroundColor = UIColor.orange
textview.translatesAutoresizingMaskIntoConstraints = false
textview.text = "chang a chang chang a chang chang a chang chang a chang"
self.view.addSubview(textview)
let size = textview.sizeThatFits(CGSize(width: 100, height: 0))
let constraint1 = NSLayoutConstraint.init(item: textview, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 10)
let constraint2 = NSLayoutConstraint.init(item: textview, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
let constraint3 = NSLayoutConstraint.init(item: textview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
let constraint4 = NSLayoutConstraint.init(item: textview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.height)
self.view.addConstraints([constraint1,constraint2,constraint3,constraint4])

setNeedsLayout和layoutIfNeeded

setNeedsLayout的作用就是標記了一個flag,表示該控件需要刷新布局,此方法記錄調整的布局請求并立即返回,它不會強制立即更新,而是會等待下一個更新周期才進行刷新頁面布局;調整視圖的子視圖的布局時,系統默認會在主線程調用此方法的;我們也可以手動調用這個方法,標記該控件是需要刷新的,這樣可以將所有的布局更新合并到一個更新周期,適合用來優化性能。
layoutIfNeeded,調用該方法會立即更新所有標記了flag的控件布局;
setNeedsLayout和layoutIfNeeded一般都是配合使用的,控件先調用setNeedsLayout再調用layoutIfNeeded就能實現立即更新布局的需求;(在控件第一次顯示之前,肯定是有flag的,所以不用setNeedsLayout直接調用layoutIfNeeded也會進行立即更新);
之前一節中的auto layout獲取布局前size使用layoutIfNeeded方法同樣能獲取到size:

label.snp.makeConstraints { (make) in
    make.leading.top.equalToSuperview().offset(20)
}
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
print(label.frame) // (20.000000000000007, 20.0, 112.66666666666667, 20.333333333333332)

在使用Autolayout時,動畫的使用和以前也不同了,frame layout時我們是修改frame,現在我們可以通過修改約束, 然后在動畫時調用layoutIfNeeded就行了:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.label?.snp.remakeConstraints { (make) in
        make.leading.top.equalToSuperview().offset(20)
        make.height.equalTo(200)
    }
    UIView.animate(withDuration: 0.5) {
        self.view.layoutIfNeeded()
    }
}

布局優先級

抗拉伸、抗壓縮優先級
    1. 抗拉伸

在講抗拉、抗壓優先級前,我們之間看一個示例:

let titleLbl = UILabel()
titleLbl.backgroundColor = .orange
titleLbl.text = "標題xxxxxxx"
view.addSubview(titleLbl)
let timeLbl = UILabel()
timeLbl.backgroundColor = .orange
timeLbl.text = "時間2019-01-01"
view.addSubview(timeLbl)

titleLbl.snp.makeConstraints { make in
    make.leading.equalTo(15)
    make.centerY.equalToSuperview()
}

timeLbl.snp.makeConstraints { make in
    make.leading.equalTo(titleLbl.snp.trailing).offset(10)
    make.trailing.equalTo(-15)
    make.centerY.equalTo(titleLbl)
}

只是一個常用的 左右布局 界面; 實際效果如下:

默認抗拉

因為約束的影響,左邊的標題label并不是自適應寬度的,寬度遠遠長過實際字符長度;
這種現象稱為被拉伸了;抗拉伸優先級顧名思義就是控制哪個控件優先不被拉伸;
上述示例默認情況,titleLbl的抗拉伸優先級低于timeLbl的抗拉伸優先級,因此titleLbl被優先拉伸,timeLbl沒有拉伸;
可通過代碼調整優先級:

open func setContentCompressionResistancePriority(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis)
titleLbl.setContentHuggingPriority(.defaultHigh, for: .horizontal)
timeLbl.setContentHuggingPriority(.defaultLow, for: .horizontal)

增加上述代碼后,實際效果:

修改優先級

如果label的背景顏色和父視圖背景顏色一樣的,只修改timeLbl的對齊方式為.right,實際上的效果和不修改抗拉伸優先級是一樣的;
但是這只是這種簡單布局的情況,如果控件多了,還是必須得設置優先級;
比如在標題后加個按鈕,按鈕固定顯示貼在標題文字右邊;

let button = UIButton(type: .detailDisclosure)
view.addSubview(button)
button.snp.makeConstraints { make in
    make.leading.equalTo(titleLbl.snp.trailing).offset(5)
    make.centerY.equalTo(titleLbl)
    make.width.height.equalTo(30)
}

默認情況、和修改優先級后的實際效果:

默認
修改優先級
  • 抗壓縮
    以上的示例是比較理想的情況:左右兩邊的文字都是在長度范圍內;
    如果標題比較長的情況,默認情況實際效果如下:
默認壓縮

標題顯示完全了,占用了大部分長度;
因此時間則只能顯示部分了,遠遠少于實際長度,這種現象稱為被拉伸了;
同樣也可以代碼跳轉抗壓縮優先級:

open func setContentCompressionResistancePriority(_ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis)

修改后的效果:

修改優先級
約束優先級

NSLayoutConstraint提供了priority屬性,以控制同一約束的優先級;

/* If a constraint's priority level is less than required, then it is optional.  Higher priority constraints are met before lower priority constraints.
     Constraint satisfaction is not all or nothing.  If a constraint 'a == b' is optional, that means we will attempt to minimize 'abs(a-b)'.
     This property may only be modified as part of initial set up or when optional.  After a constraint has been added to a view, an exception will be thrown if the priority is changed from/to NSLayoutPriorityRequired.
     */
    
    open var priority: UILayoutPriority

snpKit基于此,也封裝了該功能:

    @discardableResult
    public func priority(_ amount: ConstraintPriority) -> ConstraintMakerFinalizable {
        self.description.priority = amount.value
        return self
    }

約束優先級應用場景
動態布局:當其中一個控件不需要顯示,其余控件自動調整約束;
示例:
有3個控件緊密并排顯示;但是某些情況需要不顯示中間綠色的控件,要求其余2個控件還是緊密并排;

3個
2個

一個粗暴的做法就是,加個判斷寫2個布局;那如果要求是不顯示第一個紅色控件,其余2個自動對齊左邊,又需要寫一堆判斷;
簡單有效的做法,就是使用priority,約束自動根據優先級更新

        rBox.backgroundColor = .red
        gBox.backgroundColor = .green
        bBox.backgroundColor = .blue
        
        view.addSubview(rBox)
        view.addSubview(gBox)
        view.addSubview(bBox)
        
        rBox.snp.makeConstraints { make in
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.height.equalTo(100)
        }
        gBox.snp.makeConstraints { make in
            make.centerY.equalTo(rBox)
            make.width.height.equalTo(rBox)
            make.leading.equalTo(rBox.snp.trailing).offset(10)
            make.leading.equalTo(10).priority(.low)
        }
        bBox.snp.makeConstraints { make in
            make.centerY.equalTo(rBox)
            make.width.height.equalTo(rBox)
            make.leading.equalTo(gBox.snp.trailing).offset(10)
            make.leading.equalTo(rBox.snp.trailing).offset(10).priority(.medium)
            make.leading.equalTo(10).priority(.low)
        }

不顯示哪個控件,就直接刪除哪個控件的約束(或直接刪除控件),即可實現效果;

gBox.snp.removeConstraints()
//   gBox.removeFromSuperview()

參考:
深入理解 Auto Layout 第一彈

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,748評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,165評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,595評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,633評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,435評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,943評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,035評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,175評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,713評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,599評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,788評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,303評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,034評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,412評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,664評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,408評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,747評論 2 370

推薦閱讀更多精彩內容