0

Есть коллекция с авто размерными ячейками, также в ней присутствуют header и footer. Проблема заключается в том, что header и footer появляются не на своем месте, но если прокрутить коллекцию то header и footer станут на свои места. Также есть еще проблема с индикатором прокрутки - он почему то проходит под header, как будто header находится поверх всего (даже индикатора).

К сведению: у первой секции нет заголовка для удобства, размер установлен в 0. Также в первой секции 3 ячейки.

Подскажите как это все исправить.

layout.estimatedItemSize = CGSize(width: 1,height: 1)

введите сюда описание изображения

введите сюда описание изображения

введите сюда описание изображения

     class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {


    let cellFirst = Cell()

    let randomTexts = ["Aenean dapibus urna a ullamcorper malesuada. Ut tempor. Aenean dapibus urna a ullamcorper malesuada. Ut tempor.",
                       "Sed venenatis ligula massa, a vulputate ipsum fringilla eget. Ut justo erat, facilisis id rhoncus cursus, fringilla at.",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lobortis nibh metus, elementum tempus libero ornare vitae. Etiam sed leo pretium, consectetur turpis non, dapibus purus. Suspendisse potenti. Ut ut eros nunc. Cras nulla justo, porttitor non sapien at, iaculis.",
        "Maecenas pellentesque sed magna in congue. Sed non lacus in mi posuere scelerisque. Aenean.",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eget ex a velit tincidunt sodales. Donec elementum nisi at enim tempus, et rutrum erat semper. Phasellus ultricies est nec finibus.", "Aenean dapibus urna a ullamcorper malesuada. Ut tempor.",
        "Sed venenatis ligula massa, a vulputate ipsum fringilla eget. Ut justo erat, facilisis id rhoncus cursus, fringilla at.",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lobortis nibh metus, elementum tempus libero ornare vitae. Etiam sed leo pretium, consectetur turpis non, dapibus purus. Suspendisse potenti. Ut ut eros nunc. Cras nulla justo, porttitor non sapien at, iaculis."]




      lazy var collectionView: UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.estimatedItemSize = CGSize(width: view.frame.width, height: 1)
            let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectionView.backgroundColor = .white
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.translatesAutoresizingMaskIntoConstraints = false
            return collectionView
        }()

        override func viewDidLoad() {
            super.viewDidLoad()

            title = "Navigation Bar"

            view.addSubview(collectionView)

            NSLayoutConstraint.activate([
                collectionView.topAnchor.constraint(equalTo: view.topAnchor),
                collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
                collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
                collectionView.rightAnchor.constraint(equalTo: view.rightAnchor)
                ])


            collectionView.register(Cell.self, forCellWithReuseIdentifier: "cell")

            collectionView.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")


        }



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


        public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

            switch section {
            case 0:
                return 3
            default:
                return randomTexts.count
            }
        }

        public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
            cell.descriptionLabel.text = randomTexts[indexPath.row]
            return cell
        }




        func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {


            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! Header

            header.nameTitle = "Header"


            return header


        }




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

                if section == 0 {
                    return .zero
                }

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




        class Header: UICollectionReusableView {

    var nameTitle: String? {
        didSet {
            nameLabel.text = nameTitle
        }
    }


    let nameLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: 18)
        label.sizeToFit()
        label.textAlignment = .left
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()




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



    func setupViews() {
        backgroundColor = UIColor.blue

        addSubview(nameLabel)


        NSLayoutConstraint.activate([
            nameLabel.topAnchor.constraint(equalTo: topAnchor),
            nameLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
            nameLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 16),
            nameLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16)
            ])
    }




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


class Cell: UICollectionViewCell {


let descriptionLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 0
    label.font = UIFont.systemFont(ofSize: 14)
    label.sizeToFit()
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

var widthConstraint: NSLayoutConstraint?


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

func setupViews() {

    contentView.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)

    // Initialization code
    self.contentView.translatesAutoresizingMaskIntoConstraints = false
    let screenWidth = UIScreen.main.bounds.size.width

    widthConstraint = contentView.widthAnchor.constraint(equalToConstant: screenWidth)
    widthConstraint?.isActive = true

    contentView.autoresizingMask = .flexibleHeight

    contentView.addSubview(descriptionLabel)

    NSLayoutConstraint.activate([
        descriptionLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
        descriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        descriptionLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor),
        descriptionLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor)
        ])
}





required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
3
  • Можете приложить проект с примером где повторяется эта проблема?
    – VAndrJ
    26 окт 2017 в 7:37
  • window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.rootViewController = UINavigationController(rootViewController: ViewController())
    – sL.1m
    26 окт 2017 в 10:24
  • Этот код в AppDelegate добавить. В didFinishLaunchingWithOptions
    – sL.1m
    26 окт 2017 в 10:26

2 ответа 2

0

По индикатору скролла в Вашем

class Header: UICollectionReusableView {

добавьте:

override func layoutSubviews() {
    super.layoutSubviews()
    layer.zPosition = 0
}

Из простейшего в данном сценарии замените:

layout.estimatedItemSize = CGSize(width: view.frame.width, height: 1)

на

layout.estimatedItemSize = CGSize(width: view.frame.width, height: CGFloat.leastNormalMagnitude)
3
  • Спасибо. Я этот момент уже подправил. Но вот что делать с индикатором скролла не знаю.
    – sL.1m
    27 окт 2017 в 6:34
  • @sL.1m обновил ответ
    – VAndrJ
    27 окт 2017 в 8:48
  • Спасибо большое
    – sL.1m
    27 окт 2017 в 9:50
0

В случае с хедерами был такой у меня баг xCode: надо дефолтовые значения изменить хотя бы на единицу.

В моем случае высота хедера не менялась, но вдруг и на расположение это влияет? 0_о

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.