gpt4 book ai didi

swift - 将图像添加到 UICollection header Swift

转载 作者:可可西里 更新时间:2023-11-01 01:07:24 29 4
gpt4 key购买 nike

我希望在 Collection View 的 header 中实现图像。这是我到目前为止的代码,但在我测试时没有出现标题。我错过了什么吗?

    func collectionView(_ collectionView: UICollectionView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
let image = UIImageView()
image.frame = CGRect(x: collectionView.frame.width - 10 , y: 0, width: 20, height: 20)
image.image = UIImage.init(named: "trophyCase")
view.addSubview(image)
return view
}

最佳答案

UICollectionViewDelegate 不提供像 viewForHeaderInSection 这样的方法

相反,您可以使用 UICollectionViewDataSourceviewForSupplementaryElementOfKind 方法

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionView.elementKindSectionHeader else {
fatalError("Unrecognized element of kind: \(kind)")
}

let view: ReusableHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kind, for: indexPath) as! ReusableHeaderView
view.imageView.image = UIImage.init(named: "trophyCase")
view.imageView.frame = CGRect(x: collectionView.frame.width - 10 , y: 0, width: 20, height: 20)
return view
}

您还需要注册 elementKindSectionHeader

collectionView.register(ReusableHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: UICollectionView.elementKindSectionHeader)

以下是您的ReusableHeaderView

class ReusableHeaderView: UICollectionReusableView {
let imageView = UIImageView()

override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupUI()
}

private func setupUI() {
self.addSubview(imageView)

// Instead of settings imageView.frame, add following to use autolayout constraints
self.imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: self.topAnchor),
imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10.0),
imageView.widthAnchor.constraint(equalToConstant: 20.0),
imageView.heightAnchor.constraint(equalToConstant: 20.0)
])
}

}

关于swift - 将图像添加到 UICollection header Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55425704/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com