1. 程式人生 > >swift tableview cell自適應高度

swift tableview cell自適應高度

自適應高度達到的效果


實現方法:

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

5. 讓label bb顯示全部文字

選中Label bb 將屬性面板中lines 設為0,另外還要將aaa Label中 content hugging priority 中vertical設為250,同時給aaa 加入height的設定


6. view controller 類中填入程式碼

@IBOutletweakvar commentTable:UITableView!

overridefunc viewDidLoad() {

super.viewDidLoad()

commentTable.estimatedRowHeight =44.0

commentTable.rowHeight =UITableViewAutomaticDimension