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
    }
}
    
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小賢 的頭像
    小賢

    小賢的部落格

    小賢 發表在 痞客邦 留言(0) 人氣()