#2 [iOS充電]AutoLayout中的intrinsic size是什麼

語言: CN / TW / HK

今天繼續拾遺AutoLayout中一些不熟悉的概念

  • As a recap, in order for Auto Layout to render the position and size of a view correctly, Auto Layout engine must know or able to calculate the :
    • x position of a view
    • y position of a view
    • width of a view
    • height of a view

回顧並總結,AutoLayout為了正確渲染一個View的位置和大小,需要知道它的x, y, width, height

  • If you place a view without enough constraint to calculate its width and height, Xcode would complain by showing you red lines. image.png
  • Now lets place a label and define the same leading and top constraints.
  • Wait... Xcode doesn't complain even though the size is not defined and it show us blue line, what happened? image.png 如果放置一個View,沒有設定寬高相關的約束,Xcode會顯示出紅線 而如果放置一個Label,沒有出現紅線,沒有約束的錯誤 為什麼呢?
  • It turns out that Auto Layout Engine is able to calculate the label size (width and height) based on its content (text of the label) and the font type/size of the label. For the label using System font type, font size 17pt and contain text "Lorem Ipsum", its intrinsic size is as follows : image.png 事實證明,AutoLayout可以基於內容計算label的size。對於label使用的確定的字型、字號,它的intrinsic size(內在size)如圖顯示
  • Intrinsic content size means the size of an UI element derived based on its content. Intrinsic content size意味著一個UI元素的size由其內容所衍生

    這個概念我是在工作中開發需求時學習到的。leader告訴我label可以把frame“撐開”,不用手動計算label的frame的大小,我一臉不信,leader給了我一個白眼......現在知道這玩意兒叫Intrinsic size了,還是我太菜了

  • UIView doesn't have intrinsic content size hence you have to manually define constraints that enable Auto Layout Engine to calculate its size.
  • Label / UILabel has intrinsic content size, its width and height can be derived from the text of the label and the font type/size used.
  • Button and Textfield has intrinsic content size and its calculation is similar to label. label擁有intrinsic size,button和textField也類似,而UIView沒有
  • An empty image view doesn't have intrinsic content size, but once you add image to the image view, its intrinsic content size is set to the image size. 空白UIImageView沒有intrinsic size,但添加了image之後就有了
  • If you set both explicit width and height constraint, or leading/trailing and top/bottom constraint for the label, the explicit defined size or calculated size from constraints will replace the intrinsic content size making it fixed and non flexible. This causes problem if the text of label exceed the size and unable to expand, causing the text to be cropped : image.png 如果你顯式地設定label的寬高約束,會替代label的intrinsic size。這回導致如果label的文字顯示不下,label也無法被撐開,文字會被截斷

  • Intrinsic content size allows the size of an UI element to be dynamically expanded based on its content, it is especially useful on designing a scroll view containing dynamic content (content loaded from user input or HTTP request) or self sizing table view cells (tableview containing rows of different height based on the content of the label inside cell).

intrinsic size對於scrollView非常實用,以及自適應tableViewCells(包含不同高度由內部內容決定的tableView)