Cli*_*int 2 ios uicollectionview swift
我有一个带有显示用户信息的部分标题的集合视图。标题可以包括来自用户的个人简介。如果 bio 很长,我在调整标题大小时会遇到问题。标签不会显示整个生物,因为标题保持在一个固定的高度。
我通过故事板创建了集合视图,但是我以编程方式添加了约束。
这是生物限制,我想通过将高度和线条设置为 0 就可以了,
addSubview(bioLabel)
bioLabel.anchor(top: editProfileButton.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 12, paddingLeft: 12, paddingBottom: 0, paddingRight: 12, width: 0, height: 0)
Run Code Online (Sandbox Code Playgroud)
我还认为我可以通过以下方式覆盖故事板
// Trying to override storyboard header height so the header can strech depending on the bio height
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//TODO change height to be bounds.height of bioLabel?
return .init(width: view.frame.width, height: 300)
}
Run Code Online (Sandbox Code Playgroud)
但即使我尝试通过代码更改大小,它也会将故事板高度保持为 225(这是我想要的)
小智 7
到目前为止给出的答案都不是好的做法,因为手动计算大小或通过在屏幕外渲染标签既低效又违反单一事实来源原则。
实例UICollectionReusableView有preferredLayoutAttributesFitting()方法。当单元格显示时,将调用此方法。在这种方法中,如果您使用自动布局,您会询问整个单元格systemLayoutSizeFitting(),然后修改属性。然后布局将负责通过布局失效来应用它们。