представление вложенной коллекции, не изменяющее размер внутри таблицы размеров ячейки - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь создать макет, подобный this

. Для этого я пытаюсь получить представление таблицы с самоопределением размеров и внутри нее представление сбора с самоопределением размеров с горизонтальной прокруткой ячеек. Я использую autolayout во внешней ячейке табличного представления, а также в ячейке коллекционного представления для поддержки самоконтроля. Для горизонтальной прокрутки я добавляю отдельный UICollectionViewController и добавляю его представление в качестве подпредставления в ячейку табличного представления. Проблема в том, когда я устанавливаю примерную высоту строки таблицы. Представление коллекции обрезается, и его высота составляет 0,5

Вот мой домашний контроллер представления таблицы

class ViewController: UITableViewController {

    fileprivate let cellId = "cellId1"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        view.backgroundColor = .white

        print("vd")

        tableView.register(YourCircleTableCell.self, forCellReuseIdentifier: cellId)

        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableView.automaticDimension

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! YourCircleTableCell


        return cell
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 500
//    }




}

Вот моя ячейка представления таблицы

class YourCircleTableCell: UITableViewCell {

    let topLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "YOUR CIRCLE"
        label.textColor = UIColor(red: 138/255, green: 138/255, blue: 143/255, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        return label
    }()

    let headingLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "London grabbs by friends"
        label.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        return label
    }()

    let controller = YourCircleCollectionController()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

//        contentView.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(topLabel)

        topLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true
        topLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 24).isActive = true

        contentView.addSubview(headingLabel)

        headingLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true
        headingLabel.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 6).isActive = true

        let controllerView = controller.view
        contentView.addSubview(controllerView!)
        controllerView?.translatesAutoresizingMaskIntoConstraints = false

        controllerView?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0).isActive = true
        controllerView?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0).isActive = true
        controllerView?.topAnchor.constraint(equalTo: headingLabel.bottomAnchor, constant: 16).isActive = true
        controllerView?.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -24).isActive = true

//        controllerView?.heightAnchor.constraint(equalToConstant: 120).isActive = true


    }

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

    //    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
//
//        self.contentView.frame = self.bounds
//        self.contentView.layoutIfNeeded()
//
//        return self.controller.collectionView.contentSize
//
//    }


}

Горизонтальный контроллер сбора, который я добавляю к содержимому ячейки табличного представленияРазмер

class YourCircleCollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    fileprivate let id = "id"

    init() {

        super.init(collectionViewLayout: UICollectionViewFlowLayout())

    }

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

    override func viewDidLoad() {
        super.viewDidLoad()

        print("collection controller added")
        collectionView.backgroundColor = .white

        collectionView.register(YourCircleCollectionCell.self, forCellWithReuseIdentifier: id)

        if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
//            layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        }



    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! YourCircleCollectionCell
        cell.backgroundColor = .white
        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 8
    }

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



        return .init(width: 120, height: self.view.frame.height)
    }    

}

И, наконец, ячейка просмотра совокупности

class YourCircleCollectionCell: UICollectionViewCell {

    let userImage: UIImageView = {
        let iv = UIImageView(image: #imageLiteral(resourceName: "2"))
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.heightAnchor.constraint(equalToConstant: 64).isActive = true
        iv.widthAnchor.constraint(equalToConstant: 64).isActive = true
        iv.contentMode = .scaleAspectFill
        iv.layer.cornerRadius = 32
        return iv
    }()

    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "You"
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textAlignment = .center
        return label
    }()

    let grabbCountLabel: UILabel = {
        let label = UILabel()
        label.text = "89 grabs"
        label.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        label.textAlignment = .center
        label.textColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
        return label
    }()

//    lazy var width: NSLayoutConstraint = {
//        let width = contentView.widthAnchor.constraint(equalToConstant: bounds.size.width)
//        width.isActive = true
//        return width
//    }()

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

        contentView.translatesAutoresizingMaskIntoConstraints = false

        contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        contentView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

        let stackView = UIStackView(arrangedSubviews: [userImage, nameLabel, grabbCountLabel])
        stackView.axis = .vertical
        stackView.spacing = 8
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.alignment = .center

        contentView.addSubview(stackView)
        stackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true

        stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
        stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

        stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true




    }

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

//    var isHeightCalculated: Bool = false
//
//
//    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//        if !isHeightCalculated {
//            setNeedsLayout()
//            layoutIfNeeded()
//            let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
//            var newFrame = layoutAttributes.frame
//            newFrame.size.width = CGFloat(ceilf(Float(size.width)))
//            layoutAttributes.frame = newFrame
//            isHeightCalculated = true
//        }
//        return layoutAttributes
//    }




}

Не работает также использование предпочитаемый элементLayoutAttributesFitting

Поскольку представление коллекции полностью обрезается в ячейке табличного представления , как это

Представление коллекции отображается только при настройке значений Расчетная высота строки и реализация systemlayoutsizefitting

Но это не Dynami c. Я застрял на этом и хочу, чтобы Dynami c поддерживал как внешнюю ячейку табличного представления, так и вложенный просмотр коллекции

Пожалуйста, кто-нибудь указывает мне правильное направление, так как этот подход будет использоваться для всех ячеек табличного представления с разными вложенными представлениями коллекции

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...