Как последовательно отображать данные массива в нескольких ячейках в разделе таблицы? Xcode - PullRequest
0 голосов
/ 08 апреля 2020

В моем проекте в настоящее время у меня есть 3 символа в разных ячейках представления коллекции. При нажатии вид переходит к табличному виду для отображения имени и фотографии этого персонажа. Есть 2 раздела, которые я создал, используя структуры. Первый раздел содержит только 1 ячейку, отображающую его биографию. Второй раздел содержит 3 ячейки для отображения символов 3 отдельных навыков. Я получил био раздел, работающий отлично, используя массив и 1 ячейку таблицы, но я не могу понять, как правильно отобразить раздел навыков персонажей, используя массив в 3 ячейки таблицы. Мой код пропускает первый элемент массива умений и повторяет одинаковые умения для каждого персонажа. Мой код для моего collectionView и tableView выглядит следующим образом:

******************** Файл TableView *********** *******

import UIKit

struct cellData {

    var opened = Bool()
    var text = String()
    var sectionData = [String]()
}

class CharacterDetailViewController: UIViewController{

    let characterSkills: [UIImage] = [
    UIImage(named: "Character1-1")!,
    UIImage(named: "Character1-2")!,
    UIImage(named: "Character1-3")!,
    UIImage(named: "Character2-1")!,
    UIImage(named: "Character2-2")!,
    UIImage(named: "Character2-3")!,
    UIImage(named: "Character3-1")!,
    UIImage(named: "Character3-2")!,
    UIImage(named: "Character3-3")!,
    ]

    let characterSkillsName = [/*Character1*/"Skill1-1", "Skill1-2", "Skill1-3", "Skill2-1", "Skill2-2", "Skill2-3", "Skill3-1", "Skill3-2", "Skill3-3"]

//Outlets

    @IBOutlet var mainView: UIView!
    @IBOutlet weak var tableView: UITableView!

//Variables

    var tableViewData = [cellData]()
    var characterName = ""
    var characterDesc = ""

    var currentColor = UIColor()

//Functions

    override func viewDidLoad() {
        super.viewDidLoad()

        mainView.backgroundColor = currentColor
        tableView.backgroundColor = currentColor


        tableViewData = [cellData(opened: false, text: "Bio", sectionData: [characterDesc]),
        cellData(opened: false, text: "Skills", sectionData: ["", "", ""])]

        // For Custom Cells
        tableView.register(SkillsTableViewCell.nib(), forCellReuseIdentifier: SkillsTableViewCell.identifier)

        //Header Setup - Start

        let header = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 360))
        header.backgroundColor = currentColor

        let characterImage = UIImage(named: characterName)
        let imageView = UIImageView(image: characterImage)

        imageView.frame = CGRect(x: mainView.center.x, y: 0, width: 150, height: 150)
        header.addSubview(imageView)
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = imageView.bounds.width / 2
        imageView.layer.borderColor = UIColor.white.cgColor
        imageView.layer.borderWidth = 5

        let nameLabel = UILabel(frame: header.bounds)
        //this enables autolayout
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        header.addSubview(nameLabel)
        nameLabel.text = characterName
        nameLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10).isActive = true
        nameLabel.widthAnchor.constraint(equalToConstant: mainView.bounds.width).isActive = true
        nameLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
        nameLabel.textAlignment = .center
        nameLabel.font = .boldSystemFont(ofSize: 30)

        tableView.tableHeaderView = header
        //Header Setup - Finish
    }
}

extension CharacterDetailViewController: UITableViewDelegate, UITableViewDataSource{

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if tableViewData[section].opened == true {
            return tableViewData[section].sectionData.count + 1
        } else {
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dataIndex = indexPath.row - 1
        if indexPath.row == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
            cell.textLabel?.text = tableViewData[indexPath.section].text
            cell.contentView.backgroundColor = currentColor
            return cell

        } else if indexPath.section == 1 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "SkillsTableViewCell", for: indexPath) as? SkillsTableViewCell else {return UITableViewCell()}
            cell.contentView.backgroundColor = .blue
            cell.skillLabel.text = characterSkillsName[indexPath.item]
            cell.skillImageView.image = characterSkills[indexPath.item]
            return cell

        } else {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell2") else {return UITableViewCell()}
            cell.textLabel?.text = tableViewData[indexPath.section].sectionData[dataIndex]
            cell.contentView.backgroundColor = currentColor
            return cell
        }
    }



    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
        if tableViewData[indexPath.section].opened == true {
            tableViewData[indexPath.section].opened = false
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none) //play around with this
        } else {
            tableViewData[indexPath.section].opened = true
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none) //play around with this
            }
        }
    }
}

***************** Файл ColectionView *************** ****

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    let characters = ["Character1", "Character2", "Character3"]

    let characterImages: [UIImage] = [
    UIImage(named: "Character1")!,
    UIImage(named: "Character2")!,
    UIImage(named: "Character3")!,
    ]

    let characterSkills: [UIImage] = [
    UIImage(named: "Character1-1")!,
    UIImage(named: "Character1-2")!,
    UIImage(named: "Character1-3")!,
    UIImage(named: "Character2-1")!,
    UIImage(named: "Character2-2")!,
    UIImage(named: "Character2-3")!,
    UIImage(named: "Character3-1")!,
    UIImage(named: "Character3-2")!,
    UIImage(named: "Character3-3")!,
    ]

    let charactersSkillsName = [[/*Character1*/"Skill1-1", "Skill1-2", "Skill1-3", /*Character2*/"Skill2-1", "Skill2-2", "Skill2-3", /*Character3*/"Skill3-1", "Skill3-2", "Skill3-3"]]

    let charactersDescriptions = [/*Character1*/"I am awesome", /*Character2*/"I am cool", /*Character3*/"I am amazing"]


    let viewColors = [UIColor.purple, UIColor.red, UIColor.orange]

    override func viewDidLoad() {
        super.viewDidLoad()

        let layout = UICollectionViewFlowLayout()
        collectionView.collectionViewLayout = layout
        layout.itemSize = CGSize(width: 130, height: 150)
        collectionView.register(MyCollectionViewCell.nib(), forCellWithReuseIdentifier: MyCollectionViewCell.identifier)
        collectionView.delegate = self
        collectionView.dataSource = self
    }

}

extension ViewController: UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        print("You tapped me")
        let vc = storyboard?.instantiateViewController(withIdentifier: "CharacterDetailViewController") as? CharacterDetailViewController
        vc?.characterName = characters[indexPath.item]
        vc?.characterDesc = charactersDescriptions[indexPath.item]
        vc?.currentColor = viewColors[indexPath.item]
        self.navigationController?.pushViewController(vc!, animated: true)
    }
}

extension ViewController: UICollectionViewDataSource {

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

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

        cell.label.text = characters[indexPath.item]
        cell.imageView.image  = characterImages[indexPath.item]        
        return cell
    }
}

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let bounds = collectionView.bounds
        return CGSize(width: bounds.width/3-10, height: bounds.height/4)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 5, left: 5, bottom: 0, right: 5)
    }

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...