我有這個uicollectionviewcell斯威夫特給予uicollectionviewcell寬度和動態高度
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = commentSection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CommentCell
return cell
}
CommentCell
:
let CommenterprofileImage: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let commentText: UILabel = {
let l = UILabel()
l.numberOfLines = 0
l.text = "some text"
l.translatesAutoresizingMaskIntoConstraints = false
return l
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .blue
designCell()
}
func designCell(){
addSubview(CommenterprofileImage)
addSubview(commentText)
addCellConstraints()
}
func addCellConstraints(){
CommenterprofileImage.topAnchor.constraint(equalTo: self.topAnchor,constant:10).isActive = true
CommenterprofileImage.leftAnchor.constraint(equalTo: self.leftAnchor,constant:20).isActive = true
CommenterprofileImage.widthAnchor.constraint(equalToConstant: 70).isActive = true
CommenterprofileImage.heightAnchor.constraint(equalToConstant: 70).isActive = true
commentText.topAnchor.constraint(equalTo: CommenterprofileImage.bottomAnchor,constant:20).isActive = true
commentText.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
commentText.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
,我想這個單元格的寬度等於view
的寬度,但我想它是高度取決於它的內容。 我試着這樣做
layout.estimatedItemSize = CGSize(width: view.frame.width, height: 100)
但後來我的手機的身高爲100,寬度小於100
你可以用字符串的有界矩形方法計算標籤高度,這會給你估計的標籤高度,因爲作爲一個內容它是一個變化,並獲得e單元格的xact高度只是將您的圖片高度與估計的高度+ y位置約束相加。其他不錯的選擇是使用UICollectionViewLayout。 –
@TusharSharma有界的矩形方法返回0 –
顯示代碼你怎麼做? –