Ячейка представления коллекции в контроллере табличного представления (например, вкладка Tinder Message)

я впервые использую Stack Overflow :) надеюсь, что смогу найти ответы и поделиться своими знаниями.

В настоящее время я делаю приложение для чата, такое как Tinder или стиль Instagram, для изучения Swift.

как вы можете видеть в Tinder, вы можете смахивать горизонтально совпадающих пользователей

https://i.stack.imgur.com/dFUcM.jpg

Я хочу построить почти такой же дизайн, как этот.

на моем main.storyboard это похоже на

TableViewController

   -collectionView

        -collectionViewCell
        -collectionViewFlowLayout

   -tableViewCell

        -contentView

как это.

Ячейка collectionView предназначена для сопоставленных пользователей, а tableviewCells — для открытых чатов.

Я уже закончил делать чаты.

но часть представления коллекции никогда не отображается. Я попытался создать файл Extension.swift для этого и набрал как

 extension TableViewController {


   class RequestCVCell: UICollectionViewCell {

    @IBOutlet weak var MatchedAvatar: UIImageView!
    @IBOutlet weak var MatchedName: UILabel!

   override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
   MatchedAvatar.layer.cornerRadius = 30
   MatchedAvatar.clipsToBounds = true

    }


    let horizontalView = UIView(backgroundColor: .blue)

          }
 }

Я думал о создании раскадровки, например

ViewController

   -collectionView

        -collectionViewCell
        -collectionViewFlowLayout

   -tableView

        -contentView

Я действительно понятия не имею, почему это не работает. :( Есть ли способ сделать как трут?

спасибо за чтение и извините за мой английский, отсутствие объяснений.


person noobmaster    schedule 02.04.2020    source источник


Ответы (1)


Я создал для вас пример проекта на github https://github.com/manojaher88/CollectionViewInTableView.

ниже приведен код, который может вам помочь

// MARK:- CellType
enum CellType: Int, CaseIterable {
    case newMatches = 0
    case messages
}

// MARK:- NewMatch
struct NewMatch {
    let name: String
    let imageName: String
}

// MARK:- ViewController
class ViewController: UIViewController {

   enum Constants {
    static let nibName = "CollectionTableViewCell"
    static let reuseIdentifier = "CollectionTableViewCell"
}

@IBOutlet weak var tableView: UITableView!

private var newMatches: [NewMatch] = []
private var newMessages: [NewMatch] = []

override func viewDidLoad() {
    super.viewDidLoad()
    setupTableView()
    createDataSource()
}

private func setupTableView() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableView.automaticDimension
    let nibName = UINib(nibName: Constants.nibName, bundle: nil)
    tableView.register(nibName, forCellReuseIdentifier: Constants.reuseIdentifier)
}

private func createDataSource() {
    for i in 0...3 {
        let newMatch = NewMatch(name: "Matches \(i)", imageName: "image_1")
        newMatches.append(newMatch)
    }

    for i in 0...3 {
        let newMatch = NewMatch(name: "Messages \(i)", imageName: "image_1")
        newMessages.append(newMatch)
    }
}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource  {

func numberOfSections(in tableView: UITableView) -> Int {
    return CellType.allCases.count
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.reuseIdentifier, for: indexPath) as? CollectionTableViewCell else {
        fatalError()
    }
    var dataSource: [NewMatch] = []
    let cellType = CellType(rawValue: indexPath.section)
    switch cellType {
    case .newMatches:   dataSource = newMatches
    case .messages:     dataSource = newMessages
    case .none: break
    }
    cell.update(newModels: dataSource)

    return cell
}
}

class CollectionTableViewCell: UITableViewCell {

enum Constants {
    static let nibName = "CollectionViewCell"
    static let reuseIdentifier = "CollectionViewCell"
}

@IBOutlet private weak var collectionView: UICollectionView!
private var models: [NewMatch] = []


override func awakeFromNib() {
    super.awakeFromNib()
    collectionView.delegate = self
    collectionView.dataSource = self
    let collectionViewCell = UINib(nibName: Constants.nibName, bundle: nil)
    collectionView.register(collectionViewCell, forCellWithReuseIdentifier: Constants.reuseIdentifier)
}

func update(newModels: [NewMatch]) {
    models.removeAll()
    models.append(contentsOf: newModels)
    collectionView.reloadData()
}
}

extension CollectionTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseIdentifier, for: indexPath) as? CollectionViewCell else {
        fatalError()
    }

    let model = models[indexPath.section]
    cell.userImage.image = UIImage(named: model.imageName)
    cell.userName.text = model.name
    return cell
}
}

class CollectionViewCell: UICollectionViewCell {

@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var userName: UILabel!

override func prepareForReuse() {
    userImage.image = nil
}
}
person Manoj    schedule 02.04.2020
comment
:oi неужели ты написал все это всего за 10 минут? :ООООООООООООоооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооооо это будет так полезно для моей учебы! - person noobmaster; 02.04.2020
comment
Если ваш вопрос решен, не могли бы вы принять ответ? - person Manoj; 02.04.2020