0

Пытаюсь сделать разделение на секции, что бы получилось примерно так введите сюда описание изображения

Пытался так : (в listСountries - хранятся заголовки, в listMathcesInСountries хранятся значения, но все разом, по этому я циклом прохожу и отделяю для каждой секции свои значения (метод createSect), в sectionData все правильно сформировалось)

введите сюда описание изображения

var sectionData = [String: [String]]()

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {

    var id = Int()
    var searchResult = Array<String>()
    var searchController = UISearchController()


    @IBOutlet weak var TableView: UITableView!

    func numberOfSections(in tableView: UITableView) -> Int {
        return listСountries.count
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return listСountries.count
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
//        if searchController.isActive {
//            return searchResult.count
//        }

        let key = listСountries[section]
        if let value = sectionData[key] {
           return value.count
        }

        return 0
      //  return (listСountries.count)
    }
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        guard let index = listСountries.index(of : title) else {
            return -1
        }
        return index
    }
    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        return listСountries
    }


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

        var  cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if (cell == nil) {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        }

        print(indexPath.row)
        let key = listСountries[indexPath.row]
        if let value = sectionData[key] {
            cell.textLabel?.text = value[indexPath.row]
        }

        return cell
    }
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView( _ tableView : UITableView,  titleForHeaderInSection section: Int)->String? {

        return listСountries[section]
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let headerView = view as! UITableViewHeaderFooterView
        headerView.textLabel?.textColor = UIColor.orange
        headerView.textLabel?.font = UIFont(name: "Avenir", size: 25.0)
    }




    private func tableView (tableView:UITableView , heightForHeaderInSection section:Int)->Float
    {
        return 50.0
    }


    func createSect() {


        for (index,item) in listIndex.enumerated() {

            var tempSection = Array<String>()
            var IndexFromTo = item.components(separatedBy: "-")
            for (index, match) in listMathcesInСountries.enumerated() {
                if (index >= Int(IndexFromTo[0])! && index < Int(IndexFromTo[1])!){
                    tempSection.append(match)

                }
            }

            sectionData[listСountries[index]] = tempSection
        }
    }
override func viewDidLoad() {
    super.viewDidLoad()

    createSect()

    searchController = UISearchController(searchResultsController: nil)

    TableView.tableHeaderView = searchController.searchBar

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false


    self.TableView.reloadData()
}

но результат выходит такой

введите сюда описание изображения

в результате у всех секций одни и те же значения, а если листнуть вниз, то выйдет ошибка в строке cell.textLabel?.text = value[indexPath.row] - индекс все границ массива. Подскажите, где я допустил ошибку ?

1 ответ 1

2

Во первых у вас ошибка в той строке где ругается компилятор:

cell.textLabel?.text = value[indexPath.row]

Обратите внимание, к примеру indexPath.row == 5, вы достаете страну под индексом 5 из списка стран и потом из массива городов value вы достаете сразу пятое значение.

Во вторых, вам необходимо доставать значение из списка стран под индексом секции:

let key = listСountries[indexPath.section]
    if let value = sectionData[key] {
        cell.textLabel?.text = value[indexPath.row]
    }

UDP: Добавление изображения для заголовка

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 60))
        let imageView = UIImageView()
        imageView.image = UIImage(named: "picture")
        view.addSubview(imageView)
        return view
    }
3
  • спасибо за помощь
    – Lolidze
    31 окт 2018 в 9:19
  • не подскажите, а как в заголовок добавить изображение ?
    – Lolidze
    31 окт 2018 в 9:58
  • 1
    @Lolidze добавил обновление 31 окт 2018 в 10:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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