Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 向UICollection标头添加图像_Swift - Fatal编程技术网

Swift 向UICollection标头添加图像

Swift 向UICollection标头添加图像,swift,Swift,我希望在集合视图的标题中实现一个图像。这是到目前为止我所拥有的代码,但在测试时没有出现标题。我错过什么了吗 func collectionView(_ collectionView: UICollectionView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() let image = UIImageView() image.frame = CGRect(x: c

我希望在集合视图的标题中实现一个图像。这是到目前为止我所拥有的代码,但在测试时没有出现标题。我错过什么了吗

    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

相反,您可以使用
UICollectionViewDataSource的
ViewforSupplmentalElementofKind
方法

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)
        ])
    }

}

创建视图子类化UICollectionReusableView

class HeaderView: UICollectionReusableView {

    let imageView: UIImageView = {
        let iv = UIImageView(image: /*put your image here*/)
        iv.clipsToBounds = true
        iv.contentMode = .scaleAspectFill
        return iv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(imageView)
        imageView.fillSuperview() // Check extension below
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as? HeaderView
    return headerView!
}
然后在ViewController中,首先为视图创建reuseIdentifier:

fileprivate let headerId = "headerId"
然后在collectionView中注册自定义视图(让我们在
viewDidLoad
中执行此操作):

在vc中将自定义视图声明为可选视图:

var headerView: HeaderView?
然后覆盖
collectionView
ViewforSupplementalElementofKind
方法以初始化
headerView

class HeaderView: UICollectionReusableView {

    let imageView: UIImageView = {
        let iv = UIImageView(image: /*put your image here*/)
        iv.clipsToBounds = true
        iv.contentMode = .scaleAspectFill
        return iv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(imageView)
        imageView.fillSuperview() // Check extension below
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as? HeaderView
    return headerView!
}
然后执行另一个
collectionView
方法,为您的
headerView
提供一个大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return .init(width: view.frame.width, height: 340) // edit width and height as you please.
}
自定义视图初始化中使用的
fillSuperView
扩展:

extension UIView {
    func fillSuperview(withPadding padding: UIEdgeInsets = .zero) {
        translatesAutoresizingMaskIntoConstraints = false
        if let superview = superview {
            topAnchor.constraint(equalTo: superview.topAnchor, constant: padding.top).isActive = true
            leftAnchor.constraint(equalTo: superview.leftAnchor, constant: padding.left).isActive = true
            rightAnchor.constraint(equalTo: superview.rightAnchor, constant: -padding.right).isActive = true
            bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -padding.bottom).isActive = true
        }
    }
}

现在它应该可以作为您的
集合视图的标题视图

在集合视图中是否有这样做的方法?