close
在tableView的cellForRow中設定(可以寫在含collectionView的tableViewCell裡,然後再call
collectionView.reloadData() collectionViewHeight.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
需搭配 (手動計算字型寬度,用auto cell會失準
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let keyword = data[indexPath.row]
return CGSize(width: keyword.width(font: UIFont.Design.subhead.pingFangfont) + 16 + 16, height: 48)
}
extension String {
private func getSize(font: UIFont?) -> CGSize {
guard let font else { return CGSize.zero }
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}
func width(font: UIFont?) -> CGFloat {
return getSize(font: font).width
}
func height(font: UIFont?) -> CGFloat {
return getSize(font: font).height
}
}
全站熱搜