我有一个 UIView(TableHeaderView),它有几个标签和 Collection View 。其中一个标签文本是在运行时设置的。所以它的高度是未知的。我将此 View 设置为 TableView 的标题。
let tableHeaderView = CommentsTableHeaderView.instanceFromNib() as! CommentsTableHeaderView
commentsTable.tableHeaderView = tableHeaderView
在 CommentsTableHeaderview 类中,我有以下代码。 我已将 postDesc 标签的行数设置为 0。如果文本只有几行,它就会被截断。我希望它是动态的并显示所有文本。
class CommentsTableHeaderView: UIView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var postDesc: UILabel!
@IBOutlet weak var profileName: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var imageCollectionView: UICollectionView!
@IBOutlet weak var numberOfComments: UILabel!
class func instanceFromNib() -> UIView {
return UINib(nibName: "CommentsTableHeaderView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
override func awakeFromNib() {
imageCollectionView.delegate = self
imageCollectionView.dataSource = self
imageCollectionView.register(UINib(nibName: "InnerCollectionCell", bundle: nil), forCellWithReuseIdentifier: "InnerCollectionCell")
postDesc.lineBreakMode = .byWordWrapping
postDesc.numberOfLines = 0
postDesc.text = "hi"
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("inside collection view")
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("inside cell")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerCollectionCell", for: indexPath) as! InnerCollectionCell
cell.cellImageView.image = UIImage(named: "Recipe.jpeg")
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
print("inside size\(collectionView.frame.width)")
return CGSize(width: imageCollectionView.frame.width, height: 200)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
最佳答案
您需要一种方法来 resize your UILabel according to the text size .不要对 UILabel 施加高度限制。而是将其底部固定到底部 View 的顶部。
在 viewDidLoad()
之后以编程方式调整大小 - 可能在 viewWillAppear()
或 viewDidAppear()
中,然后再执行第一个 reloadData()
调用。
这是一个nice tutorial这应该如何完成 - 它建议在 viewDidLayoutSubviews()
中调整大小,这也应该没问题。
关于ios - 快速将 header 添加到具有动态高度的 uitableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925663/