Swift中動態改變TableView單元格高度


要在iOS中動態更改tableView單元格的高度,即根據可用內容調整單元格大小,我們需要使用自動尺寸屬性。我們將透過一個示例專案來說明這一點。

建立一個空專案,並轉到其viewController類,使其符合UITableViewDataSource和UITableViewDelegate。

現在,在下面的程式碼中,我們將首先建立一個表格,然後為該表格註冊一個單元格,並新增一些表格屬性。

我們將設定表格檢視委託和表格檢視資料來源。

最後,我們將表格檢視新增到檢視中。然後,我們將在檢視控制器的viewDidLoad方法中呼叫此函式。

注意:我們設定了一個名為estimatedRowHeight的屬性

func initTableView() {
   let tableView = UITableView()
   tableView.frame = self.view.frame
   tableView.dataSource = self
   tableView.delegate = self
   tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
   tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
   tableView.estimatedRowHeight = UITableView.automaticDimension
   self.view.addSubview(tableView)
}

現在,這段程式碼將一個表格新增到我們的檢視中,我們還需要告訴表格我們想要多少節和多少行。

func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5
}
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5
}

這段程式碼將在我們的表格檢視的第二行建立一些較長的文字,以便它根據內容大小獲取高度。

注意:UITableViewCell預設情況下有一個label屬性,並且label預設只有一行長度,因此我們需要更改它才能看到自動尺寸的效果。

現在我們需要告訴表格它的單元格應該有多高。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return UITableView.automaticDimension
}

執行上面的程式碼,我們將得到以下結果。

更新於:2019年7月30日

7K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告