如何解决iOS-动态调整UICollectionViewCell的宽度
我只是想动态调整单元格的大小。我遵循了几个SO问题,似乎无法产生相同的结果。 Example one Example two
我现在的代码是:
extension ItemViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = allTags[indexPath.item]
tagName.text = text //label from my custom cell (xCode not recognizing)
return CGRect(width: tagName.intrinsicContentSize.width + 60,height: 40)
}
}
在第二行中,Xcode未标识tagName。这是我的自定义单元格类的一部分。我以某种方式链接的第一个SO问题能够在sizeForItemAt中识别其单元格属性。我该如何动态调整单元格大小?我的估计尺寸确实为非零:
if let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
collectionViewLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
我想要的结果类似于照片。让我知道您是否需要更多信息。谢谢。
解决方法
x = 0.213099234 // n = 9
y = 0.2130992347 // n = 10
...
,
尝试这种方式。 在Swift5中对我来说效果很好。
首先实施 Collectionview FlowLayout委托
extension ItemViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = "Your Lable Text"
let font: UIFont = UIFont(name: "Font Name",size: 20) ?? UIFont.systemFont(ofSize: 17.0) // set here font name and font size
let width = text.SizeOf(font).width
return CGSize(width: width + 20.0,height: 40.0) // ADD width + space between text (for ex : 20.0)
}
}
添加一个字符串扩展名。
extension String {
func SizeOf(_ font: UIFont) -> CGSize {
return self.size(withAttributes: [NSAttributedString.Key.font: font])
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。