如何使单元格像标题一样固定在collectionView的顶部?

时间:2018-08-01 13:55:13

标签: ios swift uiscrollview uicollectionview uicollectionviewcell

我试图在collectionView单元内部实现searchBar,在无法使搜索栏与重新加载单元作为标头一起工作之后,我在第一个出队单元中实现了searchBar。如何为该单元格赋予类似于粘性页眉的属性,当用户向上滚动时,该标题保留在屏幕顶部,而向下滚动时则隐藏该标题?可以吗?

下面是有问题的代码

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate {

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.delegate = self
        cv.dataSource = self
        return cv
    }()

    var genericTagsArray:[String] = ["tag1","tag2","tag3","tag4","tag5","tag6","tag7","tag8","tag9","tag10","tag11","tag12","A","B","C","D","E","F","G","Ab","Abc","za","tag1","tag2","tag3","tag4","tag5","tag6","tag7","tag8","tag9","tag10","tag11","tag12","A","B","C","D","E","F","G","Ab","Abc","za"]

    var currentTagsArray:[String] = [String]() {
        didSet {
            collectionView.reloadData()
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(collectionView)
        collectionView.register(Cell.self, forCellWithReuseIdentifier: "cell")
        currentTagsArray = genericTagsArray

        collectionView.register(Header.self, forCellWithReuseIdentifier: "\(Header.self)")

        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

        collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)

    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return currentTagsArray.count + 1
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        return CGSize(width: self.view.frame.width, height: 50)
    }

    var searchCell:Header!
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 && indexPath.item == 0 {

            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(Header.self)", for: indexPath) as! Header
            cell.searchBar.delegate = self
            searchCell = cell

            DispatchQueue.main.async {
                if self.currentTagsArray.count != 0 {
                    self.searchCell?.searchBar.becomeFirstResponder()
                }
            }

            return cell
        }

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
        cell.label.text = currentTagsArray[indexPath.item - 1]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: self.view.frame.size.width, height: 50)

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.currentTagsArray = self.genericTagsArray.filter { (text) -> Bool in
            return text.contains(searchText.lowercased())
        }
    }

    var lastContentOffset:CGFloat = 0

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.lastContentOffset > self.collectionView.contentOffset.y  && self.collectionView.contentOffset.y > 0 && self.collectionView.contentOffset.y < collectionView.frame.maxY {

            self.lastContentOffset = scrollView.contentOffset.y
            searchCell.isHidden = false
        }
        else if (self.lastContentOffset < self.collectionView.contentOffset.y) && (self.collectionView.contentOffset.y < self.collectionView.frame.maxY) && (self.collectionView.contentOffset.y > 0)  {
            self.lastContentOffset = scrollView.contentOffset.y
            searchCell.isHidden = true
        }
        else{
            self.lastContentOffset = scrollView.contentOffset.y
            print("content offSet: \(scrollView.contentOffset.y)")
            print("Nothing happened")
            //  self.headerDelegate?.hideHeaderView(hide: true)
        }
    }


}

class Cell : UICollectionViewCell {

    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    func setupViews() {
        self.backgroundColor = .gray
        self.addSubview(label)
       label.translatesAutoresizingMaskIntoConstraints = false
       label.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
       label.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
       label.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
       label.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    }

}

class Header : UICollectionViewCell {

    let searchBar = UISearchBar()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    func setupViews() {
        self.backgroundColor = .gray
        self.addSubview(searchBar)
        searchBar.translatesAutoresizingMaskIntoConstraints = false
        searchBar.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        searchBar.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        searchBar.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        searchBar.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    }

}

0 个答案:

没有答案