我有一个UIView(TableHeaderView),它有很少的标签和集合视图。其中一个标签文本在运行时设置。所以它的高度未知。我将此视图设置为表视图的标题。
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)
}
答案 0 :(得分:1)
您需要一种方法resize your UILabel according to the text size。不要在UILabel上设置高度限制。而是将其底部固定在底视图的顶部。
请在viewDidLoad()
之后(可能在viewWillAppear()
或viewDidAppear()
之后,在您进行首次reloadData()
调用之前,以编程方式调整大小。
这是nice tutorial的处理方式-建议在viewDidLayoutSubviews()
内部进行调整大小,这也可以。
答案 1 :(得分:0)
您需要2个collectionViewDelegate方法:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: x, height: x)
}
如果您希望在referenceSizeForHeaderInSection高度字段中具有动态高度,请根据屏幕尺寸来设置高度,例如UIScreen.main.bounds.height * 0.09