오늘 셀에 텍스트에 따라서 유동적으로 움직이는걸 만들었는데 암튼 자주 쓸거같아 남깁니다
// UICollectionViewDelegateFlowLayout 구현
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item = rmItems[indexPath.item]
// 텍스트 길이에 따라 셀의 폭을 조정
let textWidth = item.weight.width(withConstrainedHeight: 40, font: UIFont.systemFont(ofSize: 17)) // weight의 길이에 따라 폭 조정
let exerciseWidth = item.exercise.width(withConstrainedHeight: 40, font: UIFont.systemFont(ofSize: 17)) // exercise의 길이에 따라 폭 조정
let maxWidth = max(textWidth, exerciseWidth) // 최대 길이에 맞춰서 폭 결정
return CGSize(width: maxWidth + 20, height: 90) // 텍스트 길이 + 여백
}
일단 셀에 델리게이트 플러워 선언하고 셀안에 만든다
extension String {
func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.width)
}
}
그리고 하단에 넓이는 계산해주는 여석을 만들어서 넣어준다 ~~~
이렇게하면 넓이는 자동으로 산출되는
앞으로도 자주 쓰자 아자자,