Content Compression Resistance和Content Hugging
本人轉載自:http://codingobjc.com/blog/2015/01/28/autolayoutzhong-de-content-compression-resistancehe-content-huggingdao-di-shi-shi-yao-yi-si/
Auto Layout中,Content Compression Resistance 和 Content Hugging 這兩個概念,從字面上很難理解它們真正的意思和用途,在蘋果官方文檔中相關描述也比較少。中文世界沒有與之對應的特別形象的中文翻譯。objc中國上,將其分別翻譯為內容壓縮阻力和內容吸附性,這可能一定程度上更加深了理解的難度。
這兩個概念,一直是一知半解,最近搜索和查看了許多文章和資料才徹底搞清楚了它們的作用,所以在此整理一下。
Intrinsic Content Size
要理解內容壓縮阻力和內容吸附性這兩個概念,首先要理解內部內容尺寸(Intrinsic Content Size)這一概念。
每個視圖都有內容壓縮阻力優先級(Content Compression Resistance Priority)和內容吸附性優先級(Content Hugging Priority)。但只有當視圖定義了內部內容尺寸后,這兩種優先級才會起作用;否則如果都沒有定義內容尺寸大小,又如何知道應該抗壓縮或者吸附至什么大小呢。
那么,內部內容尺寸是指的什么,有什么作用呢?
引用自蘋果官方Auto Layout指南里面對內部內容尺寸的描述:
Intrinsic Content Size
Leaf-level views such as buttons typically know more about what size they should be than does the code that is positioning them. This is communicated through the intrinsic content size, which tells the layout system that a view contains some content that it doesn’t natively understand, and indicates how large that content is, intrinsically.
For elements such as text labels, you should typically set the element to be its intrinsic size (select Editor > Size To Fit Content). This means that the element will grow and shrink appropriately with different content for different languages. `
什么意思呢?
簡單來說就是,像按鈕、文本標簽這類視圖控件,在布局的時候,它們自己內部比外部布局代碼更清楚自己需要多大的尺寸來顯示自己的內容。而這個尺寸就是由內部內容尺寸(intrinsic content size)來傳達的。這就相當于,內部內容尺寸告訴布局系統:“這個視圖里面包含了一些你不能理解的內容,但是我給你指出了那些內容有多大。”
由此可見,內部內容尺寸是為了實現視圖自適應大小而準備的。
Content Compression Resistance 與 Content Hugging
關于這兩個概念,最容易理解的文檔說明在UIView Class Reference文檔里面:
- contentCompressionResistancePriorityForAxis:
Returns the priority with which a view resists being made smaller than its intrinsic size.
- contentHuggingPriorityForAxis:
Returns the priority with which a view resists being made larger than its intrinsic size.
通過以上兩個接口的說明,其意義已經相當清楚了:內容壓縮阻力優先級就是視圖反壓縮的優先級,優先級越大,視圖就越不容易被壓小;內容吸附性優先級就是視圖反拉伸的優先級,優先級越大,視圖就越不容易被拉大。
例子
下面,引用一個來自stackoverflow的例子,這個例子很形象的解釋了內容壓縮阻力和內容吸附性優先級的作用。
假設,你有一個下面這樣的按鈕:
| 1 | [ Click Me ] |
按鈕與其父視圖之間的邊距約束優先級是500。
那么,如果按鈕的吸附性優先級(Hugging priority)大于500,按鈕看起來會是這樣:
| 1 | [Click Me] |
如果,吸附性優先級小于500,按鈕會是這樣:
| 1 | [ Click Me ] |
如果現在父視圖收縮了,按鈕的壓縮阻力優先級(Compression Resistance priority)大于500,它看起來會是這樣:
| 1 | [Click Me] |
否則,如果壓縮阻力優先級小于500,它會是這樣:
| 1 | [Cli..] |
如果不是這樣,很可能是其他的一些約束擾亂了你的整個布局。 例如,你可能將邊距約束優先級設置成了1000。或者可能是加一個優先級較高的寬度約束。遇到這種情況,可以試試“Editor > Size to Fit Content”命令。
總結
因此,我們可以簡單總結為:
參考
總結
以上是生活随笔為你收集整理的Content Compression Resistance和Content Hugging的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS开发之如何跳到系统设置里的各种设置
- 下一篇: 删除已经配置的类库和移除CocoaPod