UILabel 依內容動態調整大小

最近在研究mqtt,赫然發現只要靠storyboard,就能達到依照內容伸縮自如的UILabel寫法,當場驚為天人!!

於是把步驟記錄下來

width:

1. set width Greater Than or Equal (>=)

height(if UILabel is in a cell):

  1. numberOfLines = 0
  2. Set constraint of Bottom space.
  3. tableView.rowHeight = UITableViewAutomaticDimension
  4. tableView.estimatedRowHeight = 50

Then cell’s height will dynamically change too.

參考範例:https://github.com/emqtt/CocoaMQTT

參考網址:http://stackoverflow.com/questions/14438627/dynamically-change-uilabel-width-not-work-with-autolayout

節錄:
When using AutoLayout you should not update the frame property, instead modify the contraints on a view.

On the other hand, you could also let AutoLayout work for you. Make sure the numberOfLinesproperty of the label is set to 0 and the height constraint is of type Greater Than or Equal (>=). This way the layout will update automatically after setting new text on a label.

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *