как получить предметы из класса предметов - PullRequest
0 голосов
/ 20 июня 2019

У меня есть клетка (Список табличного представления) животных, и я хочу получить из класса информации о животных, что я хочу сделать, это получить имя животного и поместить его в клетку.

Это класс ViewController

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var TableViewList: UITableView!

    var NotKiller = Array<Animal>()
    var Killer = Array<Animal>()
    var Sections = ["NotKiller", "Killer"]

    override func viewDidLoad() {
        super.viewDidLoad()
        loadAnimals()
    }

    @IBAction func buAllAnimals(_ sender: Any) {
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return NotKiller.count

        } else {
            return Killer.count
        }
    }

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

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return Sections[section]
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        if indexPath.section==0 {
            cell.textLabel?.text = "" //here where I want to add the name

        } else {
            cell.textLabel?.text = "" // here where I want to add the name
        }

        return cell
    } 
    func loadAnimals(){
    //here where I add the Items in to arrays
    }
}

Это класс животных

import Foundation

class Animal {
    var Killing:String?
    var Name:String?
    var Des:String?
    var Image:String?

    init(Killing:String, Name:String, Des:String, Image:String) {
        self.Killing = Killing
        self.Name = Name
        self.Des = Des
        self.Image = Image
    }
}

Ответы [ 2 ]

1 голос
/ 20 июня 2019

Это будет сделано

if indexPath.section==0 {
    cell.textLabel?.text = NotKiller[indexPath.row].Name
} else {
    cell.textLabel?.text = Killer[indexPath.row].Name
}

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

0 голосов
/ 20 июня 2019

Попробуйте это:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    if indexPath.section==0 {
        cell.textLabel?.text = NotKiller[indexPath.row].name

    } else {
        cell.textLabel?.text = Killer[indexPath.row].name
    }

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