Пример: представление таблицы пользовательских ячеек в другое представление таблицы пользовательских ячеек - PullRequest
0 голосов
/ 10 февраля 2019

Может ли кто-нибудь поделиться примером перехода из набора пользовательских ячеек, который переключается на другой табличный вид пользовательских ячеек?Важно то, что первое табличное представление наследует информацию для второго табличного представления.

Пример:

Первая таблица:

[Изображение темы] Тема - Имя1 нажата

[Изображение темы] Тема - Имя2

[Изображение темы] Тема - Имя3

[Изображениеa Theme] Theme - Name4

Вторая таблица:

Заголовок: «Theme - Name1»

[Picture of Theme - Name1] - Название картинки

[Изображение темы - Имя1] - Имя картинки

[Изображение темы - Имя1] - Имя картинки

[Изображение темы - Имя1] - Имякартинка

[Изображение темы - Name1] - название картинки

Здесь вы можете увидеть приведенный выше пример в xCode

example

ViewController из «Тем»:

import UIKit

var myIndex = 0

let BreedArray : [breedClass] = [
breedClass(breed: "Dogs", previewImage: #imageLiteral(resourceName: "Chesapeake-Bay-Retriever-1"), innerData: [
    detailAnimals(image: #imageLiteral(resourceName: "black-dog"), name: "Black Dog"),
    detailAnimals(image: #imageLiteral(resourceName: "white-korean-jindo-800x540"), name: "White Dog"),
    detailAnimals(image: #imageLiteral(resourceName: "Chesapeake-Bay-Retriever-1"), name: "Brown Dog")]),
breedClass(breed: "Cats", previewImage: #imageLiteral(resourceName: "havana-brown-cat"), innerData: [
    detailAnimals(image: #imageLiteral(resourceName: "_99805744_gettyimages-625757214"), name: "Black Cat"),
    detailAnimals(image: #imageLiteral(resourceName: "twenty20_e47b3798-dd9b-40b1-91ef-1d820337966e-5aa3f798642dca00363b0df1"), name: "White Cat"),
    detailAnimals(image: #imageLiteral(resourceName: "havana-brown-cat"), name: "Bronw Cat")]),
breedClass(breed: "Rabbits", previewImage: #imageLiteral(resourceName: "800px_COLOURBOX8096964"), innerData: [
    detailAnimals(image: #imageLiteral(resourceName: "800px_COLOURBOX8096964"), name: "Black Rabbit"),
    detailAnimals(image: #imageLiteral(resourceName: "white-rabbit-500x500"), name: "White Rabbit"),
    detailAnimals(image: #imageLiteral(resourceName: "22547466-isolated-image-of-a-brown-bunny-rabbit-"), name: "Brown Rabbit")])
]

class TableViewController: UITableViewController {
override func viewDidLoad() {
    super.viewDidLoad()
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return BreedArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! breeds
    cell.createBreeds(breeds : BreedArray[indexPath.row])
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    myIndex = indexPath.row
    let vc = ViewController()
    vc.animalArray = BreedArray[indexPath.row].innerData
    performSegue(withIdentifier: "segue", sender: self)
}
}

Второй ViewController:

import UIKit

class ViewController: UIViewController {

var animalArray:[detailAnimals] = []

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return [animalArray].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "animalCell") as! detailAnimal
    cell.createAnimal(animal: animalArray[indexPath.row])
    return cell
}
}

Вот фактический результат:

Thread1: фатальная ошибка: Index out of range »во втором ViewController в следующей строке:« cell.createAnimal (animal: animalArray! [myIndex]) *

Образца должно быть достаточно для понимания процесса.Заранее благодарю за любую помощь!

1 Ответ

0 голосов
/ 10 февраля 2019

Пожалуйста, смотрите ниже код.Вы должны быть в состоянии понять, глядя на код

import UIKit

struct breedClass {
    var breed:String
    var previewImage:UIImage
    var innerData:[detailAnimals]
}

struct detailAnimals {
    var name:String
    var image:UIImage
}

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let BreedArray : [breedClass] = [
    breedClass(breed: "Dogs", previewImage: #imageLiteral(resourceName: "banner_home_001"), innerData: [
        detailAnimals(name: "Black Dog", image: #imageLiteral(resourceName: "best_of_ott_003")),
        detailAnimals(name: "White Dog", image: #imageLiteral(resourceName: "best_of_ott_001")),
        detailAnimals(name: "Brown Dog", image: #imageLiteral(resourceName: "best_of_ott_002"))]),
    breedClass(breed: "Cats", previewImage: #imageLiteral(resourceName: "banner_home_001"), innerData: [
        detailAnimals(name: "Black Cat", image: #imageLiteral(resourceName: "best_of_ott_003")),
        detailAnimals(name: "White Cat", image: #imageLiteral(resourceName: "best_of_ott_001")),
        detailAnimals(name: "Bronw Cat", image: #imageLiteral(resourceName: "best_of_ott_002"))]),
    breedClass(breed: "Rabbits", previewImage: #imageLiteral(resourceName: "banner_home_001"), innerData: [
        detailAnimals(name: "Black Rabbit", image: #imageLiteral(resourceName: "best_of_ott_003")),
        detailAnimals(name: "White Rabbit", image: #imageLiteral(resourceName: "best_of_ott_001")),
        detailAnimals(name: "Brown Rabbit", image: #imageLiteral(resourceName: "best_of_ott_002"))])
]


@IBOutlet weak var myTV: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    myTV.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "MyCell")
    myTV.separatorStyle = .none

    myTV.delegate = self
    myTV.dataSource = self
    myTV.reloadData()
}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyCell
    cell.myImg.image = BreedArray[indexPath.row].previewImage
    cell.lbl_Title.text = BreedArray[indexPath.row].breed
    cell.selectionStyle = .none
    return cell
}

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

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = SecondViewController()
    vc.myBreedClass = BreedArray[indexPath.row]
    self.navigationController?.pushViewController(vc, animated: true)
}

}

SecondViewController

import UIKit

class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var myBreedClass:breedClass?

@IBOutlet weak var myTV: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    myTV.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "MyCell")
    myTV.separatorStyle = .none

    myTV.delegate = self
    myTV.dataSource = self
    myTV.reloadData()
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = myBreedClass?.innerData.count{
        return count
    }
    return 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let lbl = UILabel()
    lbl.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 150.0)
    lbl.text = myBreedClass?.breed ?? ""
    lbl.textAlignment = .center
    return lbl
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if let count = myBreedClass?.innerData.count{
        if count>0{
            return 150
        }
        return 0
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyCell
    cell.myImg.image = myBreedClass?.innerData[indexPath.row].image
    cell.lbl_Title.text = myBreedClass?.innerData[indexPath.row].name
    cell.selectionStyle = .none
    return cell

}

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


}
...