如何使用IOS 12在UITableViewCell内正确添加UICollectionView [英] How to properly add an UICollectionView inside UITableViewCell using IOS 12

查看:82
本文介绍了如何使用IOS 12在UITableViewCell内正确添加UICollectionView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,当我使用Xcode 10 beta时,无法在表视图单元格中正确显示集合中的某些项目.在过去的四天里,我都尽力了.

我做了一个小项目样本,以查看问题所在.
如果有人想在本地运行完整代码,请参见:

这是运行时的外观:

细胞被压扁,顶部的标签消失.我想要的是集合视图应该增长以显示所有元素,并使表格视图单元格调整大小,但是目前还没有发生,我无法弄清楚问题出在哪里.

解决方案

如果需要以下输出:

代码ViewController:

  class ViewController:UIViewController {让列表= [字符串](重复:标签",计数:10)覆盖func viewDidLoad(){super.viewDidLoad()view.addSubview(tableView)tableView.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([tableView.topAnchor.constraint(等于:view.safeAreaLayoutGuide.topAnchor),tableView.leadingAnchor.constraint(equalTo:view.leadingAnchor),tableView.bottomAnchor.constraint(等于:view.safeAreaLayoutGuide.bottomAnchor),tableView.trailingAnchor.constraint(等于:view.trailingAnchor)])tableView.reloadData()}公共惰性var tableView:UITableView = {令v = UITableView.init(frame:.zero)v.代表=自我v.dataSource =自我v.estimatedRowHeight = 44v.rowHeight = UITableViewAutomaticDimensionv.register(TableCell.self,forCellReuseIdentifier:"TableCell")返回v}()}扩展ViewController:UITableViewDelegate {}扩展ViewController:UITableViewDataSource {func tableView(_ tableView:UITableView,numberOfRowsInSection部分:Int)->诠释{返回list.count}func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)->UITableViewCell {让cell = tableView.dequeueReusableCell(withIdentifier:"TableCell",for:indexPath)为!表格单元cell.label.text ="\(列表[indexPath.row])\(indexPath.row)"返回单元}} 

TableCell:

  TableCell类:UITableViewCell {需要初始化吗?(编码器aDecoder:NSCoder){super.init(编码器:aDecoder)commonInit()}覆盖init(样式:UITableViewCellStyle,复用标识符:字符串?){super.init(样式:样式,复用标识符:复用标识符)commonInit()}func commonInit(){contentView.addSubview(label)contentView.addSubview(collectionView)updateConstraints()}覆盖func updateConstraints(){label.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([label.topAnchor.constraint(equalTo:topAnchor),label.leadingAnchor.constraint(equalTo:LeadingAnchor),label.trailingAnchor.constraint(equalTo:railingAnchor)])collectionView.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([collectionView.topAnchor.constraint(equalTo:label.bottomAnchor),collectionView.leadingAnchor.constraint(equalTo:LeadingAnchor),collectionView.bottomAnchor.constraint(equalTo:bottomAnchor),collectionView.trailingAnchor.constraint(equalTo:railingAnchor),])super.updateConstraints()}let list = [String](重复:"Task_",计数:10)公开让标:UILabel = {令v = UILabel()v.textAlignment = .center返回v}()公共懒惰var collectionView:UICollectionView = {让布局= UICollectionViewFlowLayout()layout.minimumLineSpacing = 0layout.minimumInteritemSpacing = 0让v = UICollectionView(frame:.zero,collectionViewLayout:layout)v.register(CollectionCell.self,forCellWithReuseIdentifier:"CollectionCell")v.代表=自我v.dataSource =自我v.isScrollEnabled = false返回v}()覆盖func sizeThatFits(_ size:CGSize)->CGSize {让collectionCellHeight = 50let rows = list.count/5//5:每行项目let labelHeight = 20//您可以计算字符串高度让高度= CGFloat((collectionCellHeight *行)+ labelHeight)让width = contentView.frame.size.width返回CGSize(width:width,height:height)}}扩展TableCell:UICollectionViewDataSource {func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)->诠释{返回list.count}func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)->UICollectionViewCell {让单元格= collectionView.dequeueReusableCell(withReuseIdentifier:"CollectionCell",for:indexPath)为!收集单元cell.label.text ="\(list [indexPath.item])\(indexPath.item)"返回单元}}扩展TableCell:UICollectionViewDelegate {}扩展TableCell:UICollectionViewDelegateFlowLayout {func collectionView(_ collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:IndexPath)->CGSize {返回CGSize(width:collectionView.frame.width/5,height:50)}} 

CollectionCell

  CollectionCell类:UICollectionViewCell {让填充:CGFloat = 5覆盖init(frame:CGRect){super.init(frame:框架)commonInit()}需要初始化吗?(编码器aDecoder:NSCoder){super.init(编码器:aDecoder)commonInit()}func commonInit(){backgroundColor = .yellowcontentView.addSubview(label)updateConstraints()}覆盖func updateConstraints(){label.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([label.topAnchor.constraint(equalTo:topAnchor,常数:padding),label.leadingAnchor.constraint(equalTo:LeadingAnchor,常数:padding),label.trailingAnchor.constraint(equalTo:railingAnchor,常数:-padding),label.bottomAnchor.constraint(equalTo:bottomAnchor,常数:-padding)])super.updateConstraints()}公开让标:UILabel = {令v = UILabel()v.textColor = .darkTextv.minimumScaleFactor = 0.5v.numberOfLines = 1返回v}()} 

For some reasons I cannot properly display some items from a collection inside an tableview cell when using Xcode 10 beta. I tried all I know for the last 4 days.

I made a small project sample to see what my issue is.
Full code is here if someone wants to run it locally: https://github.com/adrianstanciu24/CollectionViewInsideUITableViewCell

I first add an table view with 2 different resizable cells, first cell has the collection view and a label:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 44
        tableView.rowHeight = UITableView.automaticDimension
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "collCell") as! CollectionTableViewCell
            cell.collectionView.collectionViewLayout.invalidateLayout()

            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "normalCell")!

            return cell
        }
    }
}

Here is the cell with collection view defined. This also has a height constraint which I updated in layoutSubviews:

class CollectionTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!


    override func awakeFromNib() {
        super.awakeFromNib()

        collectionView.delegate = self
        collectionView.dataSource = self

        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "taskCell", for: indexPath as IndexPath) as! TaskCollectionViewCell

        cell.name.text = "Task_" + String(indexPath.row)

        return cell
    }
}

Below is a screenshot with the collection view constraint and how the storyboard looks:

And this is how it looks when running:

The cells are squashed and label on top disappears. What I want is the collection view should grow to show all elements and also making table view cell to resize, but that is not happening at the moment and I can't figure out where the issue is.

解决方案

If you want the following output:

Code ViewController:

class ViewController: UIViewController {
    let list = [String](repeating: "Label", count: 10)
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
            ])
        tableView.reloadData()
    }

    public lazy var tableView: UITableView = { [unowned self] in
        let v = UITableView.init(frame: .zero)
        v.delegate = self
        v.dataSource = self
        v.estimatedRowHeight = 44
        v.rowHeight = UITableViewAutomaticDimension
        v.register(TableCell.self, forCellReuseIdentifier: "TableCell")
        return v
    }()
}
extension ViewController: UITableViewDelegate{

}
extension ViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
        cell.label.text = "\(list[indexPath.row]) \(indexPath.row)"
        return cell
    }
}

TableCell:

class TableCell: UITableViewCell{

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    func commonInit(){
        contentView.addSubview(label)
        contentView.addSubview(collectionView)
        updateConstraints()
    }

    override func updateConstraints() {
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: topAnchor),
            label.leadingAnchor.constraint(equalTo: leadingAnchor),
            label.trailingAnchor.constraint(equalTo: trailingAnchor)
            ])
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: label.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
            collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
            ])
        super.updateConstraints()
    }

    let list = [String](repeating: "Task_", count: 10)
    public let label: UILabel = {
        let v = UILabel()
        v.textAlignment = .center
        return v
    }()

    public lazy var collectionView: UICollectionView = { [unowned self] in
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
        v.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
        v.delegate = self
        v.dataSource = self
        v.isScrollEnabled = false
        return v
    }()

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let collectionCellHeight = 50
        let rows = list.count / 5 // 5: items per row
        let labelHeight = 20 // you can calculate String height
        let height = CGFloat((collectionCellHeight * rows) + labelHeight)
        let width = contentView.frame.size.width
        return CGSize(width: width, height: height)
    }
}
extension TableCell: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
        cell.label.text = "\(list[indexPath.item])\(indexPath.item)"
        return cell
    }
}
extension TableCell: UICollectionViewDelegate{

}
extension TableCell: UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width/5, height: 50)
    }
}

CollectionCell

class CollectionCell: UICollectionViewCell{
    let padding: CGFloat = 5
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit(){
        backgroundColor = .yellow
        contentView.addSubview(label)
        updateConstraints()
    }

    override func updateConstraints() {
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
           label.topAnchor.constraint(equalTo: topAnchor, constant: padding),
            label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
            label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding),
            label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)
            ])
        super.updateConstraints()
    }

    public let label: UILabel = {
        let v = UILabel()
        v.textColor = .darkText
        v.minimumScaleFactor = 0.5
        v.numberOfLines = 1
        return v
    }()
}

这篇关于如何使用IOS 12在UITableViewCell内正确添加UICollectionView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆