[РЕШЕНО]Создание массива CollapsibleSections


#1

Добрый день! Вдохновленный уроком по CollapsibleSections решил сделать немного сложнее реализация для себя. Суть такова - есть массив моделей с Реалма, которые возвращаются в массиве. Хочу сделать отображение в таблице с возможностью как в уроке, но чтоб были Хидер и Футер для секции.

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

struct SectionModel {
var sectionName: String
var subPoints: [String]
var expandable: Bool
}
var sectArrModel: [[SectionModel]] = []

и заполнение

func setupSections() {
        guard let data = model else { return }
        var sectArr: [SectionModel] = []
        
        var company: [String] = []
        var created: [String] = []
        var networks: [String] = []
        var languages: [String] = []
        var genres: [String] = []
        var airDate: [String] = []
        var prod: [String] = []
        
        data.forEach { (detailsModel) in
            sectArr = []
            detailsModel.production_companies.forEach({ (companyName) in
                company.append(companyName.name)
            })
            detailsModel.created_by.forEach({ (create) in
                created.append(create.name)
            })
            detailsModel.networks.forEach({ (network) in
                networks.append(network.name)
            })
            detailsModel.languages.forEach({ (language) in
                languages.append(language)
            })
            detailsModel.genres.forEach({ (genre) in
                genres.append(genre.name)
            })
            let firstDate = "First air date:" + (detailsModel.first_air_date)
            let lastDate = "Last air date: " + (detailsModel.last_air_date ?? "???")
            airDate.append(firstDate)
            airDate.append(lastDate)
            
            var production: String
            if detailsModel.in_production {
                production = "Next episode: " + (detailsModel.next_episode_to_air)
            } else {
                production = "Last episode: " + (detailsModel.last_episode_to_air?.air_date ?? "")
            }
            prod.append(production)
            sectArr.append(SectionModel(sectionName: "Production company:", subPoints: company, expandable: true))
            sectArr.append(SectionModel(sectionName: "Created by: ", subPoints: created, expandable: false))
            sectArr.append(SectionModel(sectionName: "Networks: ", subPoints: networks, expandable: false))
            sectArr.append(SectionModel(sectionName: "Languages: ", subPoints: languages, expandable: false))
            sectArr.append(SectionModel(sectionName: "Genres: ", subPoints: genres, expandable: false))
            sectArr.append(SectionModel(sectionName: "AirDate", subPoints: airDate, expandable: false))
            sectArr.append(SectionModel(sectionName: "Episode", subPoints: prod, expandable: false))
            sectArrModel.append(sectArr)
        }
    }

как мне получить количество subPoints.count для numberOfRowsInSection? возможно что то не так делаю

модель из Реалма
> 2 elements

  ▿ 0 : TVDetailsModel {
	backdrop_path = /cJotBRRn7zj4Ed95ibusfU4pqis.jpg;
	created_by = List<CreatedBy> <0x60000165d710> (
		[0] CreatedBy {
			id = 209343;
			credit_id = 525970fd760ee34661a35e79;
			name = Brian K. Vaughan;
			profile_path = /faBIScpkpGlVQAjRIRuD2tLUu2k.jpg;
		}
	);
	episode_run_time = List<int> <0x60000165e370> (
		[0] 42
	);
	first_air_date = 2013-06-24;
	genres = List<Genre> <0x60000165ea30> (
	
	);
	homepage = http://www.cbs.com/shows/under-the-dome/;
	id = 46331;
	in_production = 0;
	languages = List<string> <0x60000165e2e0> (
		[0] en
	);
	last_air_date = 2015-09-10;
	name = Under the Dome;
	next_episode_to_air = ;
	networks = List<Genre> <0x60000165d440> (
	
	);
	number_of_episodes = 39;
	number_of_seasons = 3;
	origin_country = List<string> <0x60000165ed90> (
		[0] US
	);
	original_language = en;
	original_name = Under the Dome;
	overview = Under the Dome is based on the novel of the same name by Stephen King. It tells the story of the residents of the small town of Chester's Mill in Maine, where a massive, transparent, indestructible dome suddenly cuts them off from the rest of the world. With no Internet access, no mobile signals and limited radio communication, the people trapped inside must find their own ways to survive with diminishing resources and rising tensions. While military forces, the government and the media positioned outside of this surrounding barrier attempt to break it down, a small group of people inside attempt to figure out what the dome is, where it came from, and when (and if) it will go away.;
	popularity = 15.106;
	poster_path = /iFnCH70twxNDICQlDuCcoEt4Jma.jpg;
	production_companies = List<ProductionCompany> <0x60000165e490> (
		[0] ProductionCompany {
			id = 7671;
			name = Amblin Television;
			logo_path = /r7KeUsNVv0iggZRh6XmNNq2OEw1.png;
			origin_country = US;
		},
		[1] ProductionCompany {
			id = 35828;
			name = Baer Bones;
			logo_path = /jfTbUMfToB9ZSRTkTGIPUgJ1UlF.png;
			origin_country = US;
		},
		[2] ProductionCompany {
			id = 1081;
			name = CBS Television Studios;
			logo_path = /vfcpaPf6WktaCIHqF4FJAcek8q2.png;
			origin_country = US;
		}
	);
	seasons = List<Genre> <0x60000165e880> (
	
	);
	status = Ended;
	type = Scripted;
	vote_average = 6.2;
	vote_count = 442;
}
  ▿ 1 : TVDetailsModel {
	backdrop_path = /msguUGjLhDdyB39JkmOZOXDkPRw.jpg;
	created_by = List<CreatedBy> <0x60000165f0f0> (
		[0] CreatedBy {
			id = 13620;
			credit_id = 56326366c3a3681b5e01284d;
			name = William Hanna;
			profile_path = /3rCaagU4QRi0JJhcdbUGKoqEWtG.jpg;
		},
		[1] CreatedBy {
			id = 13594;
			credit_id = 5632637b925141284c013220;
			name = Joseph Barbera;
			profile_path = /A8Lorvx5HirKefQWmhftWGO5VI4.jpg;
		}
	);
	episode_run_time = List<int> <0x60000165ef40> (
		[0] 24,
		[1] 30
	);
	first_air_date = 1961-09-27;
	genres = List<Genre> <0x60000165d5f0> (
	
	);
	homepage = ;
	id = 4232;
	in_production = 0;
	languages = List<string> <0x60000165e9a0> (
		[0] no,
		[1] en,
		[2] pl
	);
	last_air_date = 1962-04-18;
	name = Top Cat;
	next_episode_to_air = ;
	networks = List<Genre> <0x60000165ed00> (
	
	);
	number_of_episodes = 30;
	number_of_seasons = 1;
	origin_country = List<string> <0x60000165e7f0> (
		[0] US
	);
	original_language = en;
	original_name = Top Cat;
	overview = Top Cat is a Hanna-Barbera prime time animated television series which ran from November 26, 1961 to April 18, 1962 for a run of 30 episodes on the ABC network. Reruns are played on Cartoon Network's classic animation network Boomerang.;
	popularity = 4.809;
	poster_path = /jw1IR7N9n486GFWannAmAtrQZu9.jpg;
	production_companies = List<ProductionCompany> <0x60000165f060> (
	
	);
	seasons = List<Genre> <0x60000165eb50> (
	
	);
	status = Ended;
	type = Scripted;
	vote_average = 7;
	vote_count = 48;
}

#2

вот эти все переменные

var company: [String] = []
var created: [String] = []
var networks: [String] = []
var languages: [String] = []
var genres: [String] = []
var airDate: [String] = []
var prod: [String] = []

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


#3

это поправил, но как добраться к subPoints?


#4

let rowData = sectionArray[indexPath.section].subPoints[indexPath.row]

вы про это?


#5

да. только мне нужно получить это кол-во в numberOfRowsInSection чтоб отобразить нужное кол-во ячеек в секции, а у numberOfRowsInSection есть только section: Int


#6

return sectionArray[section].subPoints.count


#7

у меня же вложенность var sectArrModel: [[SectionModel]] = [] и при таком варианте я получаю [SectionModel]


#8

а зачем?
мне кажется вы сами перемудрили :slight_smile:


#9

Для данного решения пришлось реализовать таблице в секции. Модель для заполнения имеет вид var sectArrModel: [[SectionModel]] = []
выглядит вот так


типы работают, по крайнем мере в консоль печатает из метода didSelectRowAt мой indexPath.