我有一個類似的問題:

或像這樣:

或像這樣:

使用此代碼:
DemoTableViewCell
class DemoTableViewCell: UITableViewCell {
@IBOutlet var label: UILabel!
@IBOutlet var myView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
myView.layer.cornerRadius = 8
myView.layer.shadowOffset = CGSize(width: 0, height: 3)
myView.layer.shadowRadius = 3
myView.layer.shadowOpacity = 0.5
}
}
DemoTableViewController
class DemoTableViewController: UITableViewController {
let myData: [String] = [
"Single Line",
"A longer string which will wrap in Portrait Orientation",
"This string is long enough that the text will need to word-wrap (on an iPhone 8) whether in Portrait Orientation or Landscape Orientation",
"Another Single Line",
]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Demo Table"
view.backgroundColor = .systemBackground
tableView.register(UINib(nibName: "DemoTableViewCell", bundle: nil), forCellReuseIdentifier: "c")
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! DemoTableViewCell
cell.label.text = myData[indexPath.row]
return cell
}
}
在運行時,我們會得到這個:

請注意,當視圖大小發生變化時會自動處理布局:

所以,你的設計有一些問題......
首先,嘗試以UICollectionView這種方式使用 a 本質上是有問題的。集合視圖旨在布局它們的單元格,并在單元格數量超出容量時滾動。
通過使用相反的方法——獲得顯示所有單元格所需的大小,然后調整集合視圖的大小,同時將其嵌入到表格視圖單元格中——是一項相當復雜的任務。
為了讓集合視圖確定其contentSize.height:
- 需要給它一個寬度
- 它需要獲取單元格部分和專案數
- 它需要獲取單元格的大小(特別是如果它們不是固定大小的)
- 然后需要對單元格進行布局
- 并且...這是一個異步程序
- 并且......在這種情況下,直到表格視圖布置好它的單元格,集合視圖才會得到它的寬度
試圖處理所有這些的時間安排是非常困難的。
現在,由于您放棄了集合視圖的許多好處(滾動、單元重用等),并且您可能會使用少量“專案”(如果您嘗試使用幾個一百個單元格,你可能需要重新考慮你的 UI 設計)你幾乎肯定最好自己撰寫代碼來布局視圖。
有關更多詳細資訊和代碼示例,我在這里放置了一個演示專案:https ://github.com/DonMag/TagsTableExample
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412005.html
標籤:
