0

Всем приветы! Подскажите, пожалуйста. Нахожу много похожих ответов, но собрать воедино не получается из-за отсутствия опыта. У меня есть массив с секциями типа String(sectionsInCarName) и массив с элементами экземпляра класса(cars). Нужно сделать в точности как на скрине (первая буква марки машинки соответствует букве в секции). Если можно несколько вариантов для сравнения и понимания. Большое спасибо! введите сюда описание изображения

var cars: [Car]!
let sectionsInCarName: [String] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "T", "V", "W", "X", "Z"]


//  кол-во секций
func numberOfSections(in tableView: UITableView) -> Int {
    sectionsInCarName.count
}
// количетсво строк в секции
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return cars.count
}

// имя секций
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sectionsInCarName[section]
}


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomViewCell", for: indexPath) as! CustomViewCell
        cell.backgroundColor = UIColor.clear
        let car = cars[indexPath.row]
        cell.carLabel.text = car.modelName
     
        return cell
    }


// экземпляр класса на всякий случай

let audi = Car()
        audi.modelName = "Audi"
        audi.models = ["A1", "A2", "A3", "A4"]
        audi.enginesType = ["Бензин", "Дизель", "Электро", "Гибрид"]
        audi.enginesDisplacement = ["1.2", "1.3", "1.4", "1.5"]
        audi.year = ["1980", "1981", "1982", "1983", "1984"]
        audi.body = ["Седан", "Внедорожник", "Универсал", "Хэтчбэк", "Лифтбэк", "Минивэн", "Купе", "Кабриолет"]
        audi.transmission = ["МКПП", "АКПП"]
        cars.append(audi)
2
  • Добавьте код в виде текста, а не картинки
    – schmidt9
    21 окт 2021 в 10:08
  • Добавил, буду благодарен за ответ
    – ispromt
    21 окт 2021 в 16:47

1 ответ 1

0

Вот упрощенный пример, для вывода в секциях здесь создана модель секций с массивами машин по алфавиту

class CarsTableViewController: UITableViewController {
    
    struct Car {
        var modelName: String
    }

    struct Section {
        var title: String
        var cars: [Car]
    }
    
    var sections = [Section]()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadSections()
    }
    
    func loadSections() {
        
        let cars = [
            Car(modelName: "Audi"),
            Car(modelName: "Aston Martin"),
            Car(modelName: "BMW"),
            Car(modelName: "Bentley"),
            Car(modelName: "Toyota"),
            Car(modelName: "Tatra")
        ].sorted { car1, car2 in
            car1.modelName.lowercased() < car2.modelName.lowercased()
        }
        
        let sectionNames = ["A", "B", "C", "D", "T"]
        
        for sectionName in sectionNames {
            
            var section = Section(title: sectionName, cars: [])
            
            for car in cars {
                if car.modelName.starts(with: sectionName) {
                    section.cars.append(car)
                }
            }
            
            sections.append(section)
            
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        sections[section].cars.count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        sections[section].title
    }

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

        cell.textLabel?.text = sections[indexPath.section].cars[indexPath.row].modelName

        return cell
    }

}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.