swift 中cell 自適應label高度

自適應高度達到的效果

實現方法:

  1. xcode新建個項目,選擇 single View Application

  2. 打開main.storyboard 將tableview 拖到view controller中,並給tableview 拖入 tableview cell

  3. 給tableview cell 拖入 imageview 、label等控件

  4. 給控件添加 autoLayout 約束
    選中“控件Imageview或Label”,選擇 Editor,點擊“ pin ”,就能看到約束形式。

Width:寬度

Height: 高度

Leading space to superview:左間距

Trailing space to superview :右間距

top space to superview:上間距

bottom space to superview:下間距

(1)imageView 左側的圖片

爲它添加Leading space to superview、top space to superview、width、height

爲什麼沒有添加bottom space to superview,如果添加了bottom space to superview沒有設定高度,圖片就會被縱向拉伸,所以我設置了高度

爲什麼沒有設置Trailing space to superview,這個需要和label一起設置

(2)Label --aaa

爲它添加top space to superview、Trailing space to superview 、imageview和aaa之間的Horizontal space 、aaa和bb之間的 vertical space

如何添加imageview和aaa之間的Horizontal space 、aaa和bb之間的 vertical space呢?
(1)選中 image 之後,按住command鍵,選中“aaa”,選擇 Editor,點擊“ pin ”,選擇Horizontal space

(2)同時選中“aaa”和“bb”,選擇Editor,點擊“pin”,就可以添加 vertical space

(3)label -- bb

爲它添加imageview和bb之間的Horizontal space 、cc和bb之間的 vertical space、Trailing space to superview

(4)label -- cc

爲它添加imageview和cc之間的Horizontal space 、bottom space to superview、Trailing space to superview

  1. 讓label bb顯示全部文字
    選中Label bb 將屬性面板中lines 設爲0,另外還要將aaa Label中 content hugging priority 中vertical設爲250,同時給aaa 加入height的設置

  2. view controller 類中填入代碼

 @IBOutletweak var commentTable:UITableView!


override func viewDidLoad() {

        super.viewDidLoad()

commentTable.estimatedRowHeight =44.0

commentTable.rowHeight =UITableViewAutomaticDimension
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章