UICollectionView Stretchy Header

时间:2017-04-28 07:16:45

标签: swift uicollectionview

大家好我有一个带有标题的集合视图我想让它成为一个有弹性的标题当我提出任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:0)

当您向上和向下滚动UICollectionView时,可以在内容偏移更改时收到通知。例如,使用scrollViewDidScroll

如果内容偏移< 0只是更改标题子视图顶部约束,因此它看起来像标题的顶部粘在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()
    }
}

我在游乐场测试了它,但没有在真实的项目中测试过。让我知道它是否适合你。