如何解决iOS-实现自定义集合视图布局
我有一个正常的默认集合视图流布局,但是我试图使单元格保持对齐(而不是默认的中心拉伸)。我从this post得到了一些好的答案。它说我需要使用自定义布局。但是,您如何实现自定义布局呢?我创建了一个文件,就可以使用它了,但是如何使用“收藏夹视图”将其连接到VC?
这是我的收藏夹视图的VC中的内容: 在顶部的布局中创建了一个出口
@IBOutlet weak var tagsLayout: TagsLayout!
extension ItemViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
let text = allTags[indexPath.row]
let font: UIFont = UIFont(name: "Baskerville",size: 15) ?? 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: 30.0) // ADD width + space between text (for ex : 20.0)
}
//
func collectionView(_ collectionView: UICollectionView,minimumInteritemSpacingForSectionAt: Int) -> CGFloat {
return 4.0
}
}
我已经看到这在viewdidload中是必要的,但是.delegate无法识别/不在我的自定义布局中
if let layout = self.collectionView.collectionViewLayout as? TagsLayout
{
layout.delegate = self
}
TagsLayout:
import UIKit
class TagsLayout: UICollectionViewFlowLayout {
required override init() {super.init(); common()}
required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder); common()}
private func common() {
estimatedItemSize = UICollectionViewFlowLayout.automaticSize
minimumLinespacing = 10
minimumInteritemSpacing = 10
}
override func layoutAttributesForElements(
in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let att = super.layoutAttributesForElements(in:rect) else {return []}
var x: CGFloat = sectionInset.left
var y: CGFloat = -1.0
for a in att {
if a.representedElementCategory != .cell { continue }
if a.frame.origin.y >= y { x = sectionInset.left }
a.frame.origin.x = x
x += a.frame.width + minimumInteritemSpacing
y = a.frame.maxY
}
return att
}
}
解决方法
只需通过delegate
的{{1}}方法将collectionView
的{{1}}设置为self
。
viewDidLoad
然后您可以通过以下方式进行验证:
ItemViewController
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。