大家好,我有一个带标头的收藏夹视图,我希望当我提出如何实现此目的时,它会变成可伸缩的标头?

最佳答案

上下滚动UICollectionView时,内容偏移量更改时会收到通知。例如,使用scrollViewDidScroll

如果内容偏移量UICollectionView的顶部。

final class Header: UICollectionReusableView {

    lazy var subview = UIView()
    lazy var constraint: NSLayoutConstraint = NSLayoutConstraint(item: self.subview, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0)

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(subview)
        subview.backgroundColor = UIColor.orange
        subview.translatesAutoresizingMaskIntoConstraints = false
        var constraints: [NSLayoutConstraint] = []
        constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[S]|", options: [], metrics: nil, views: ["S":subview]))
        constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[S]|", options: [], metrics: nil, views: ["S":subview]))
        constraints.append(constraint)
        NSLayoutConstraint.activate(constraints)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func changed(offset: CGPoint) {
        let constant = offset.y > 0 ? 0 : offset.y
        if constant != constraint.constant {
            constraint.constant = constant
        }
        self.setNeedsLayout()
    }
}


我已经在操场上进行了测试,但没有在实际项目中进行过测试。请让我知道这对你有没有用。

关于swift - UICollectionView弹性标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43674255/

10-14 21:23