Данные повторяются в разделе UItableview

У меня есть UITableView с двумя разделами и четырьмя строками. Каждый раздел должен содержать две строки содержимого. Все работает нормально, за исключением того, что пункты повторяются в разделе 2:

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

Однако я хочу, чтобы это было так:

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

Мой код выглядит следующим образом:

быстро 4

// structure for serverData type
struct serverData {
    var structHosts: String
    var structStatusImagesMain: String
    var structServerStatusMain: String
}

Переменные для заполнения ячеек и разделов:

// data filled in my array "section" and in my array "myServerInfo" of type serverData    
let sections = ["Section 1", "Section 2"]
let myServerInfo = [
    serverData(structHosts: "www.google.com", structStatusImagesMain: "error", structServerStatusMain: "Error "), 
    serverData(structHosts: "www.amazon.com", structStatusImagesMain: "error", structServerStatusMain: "Error "), 
    serverData(structHosts: "www.ebay.com", structStatusImagesMain: "error", structServerStatusMain: "Error "), 
    serverData(structHosts: "www.apple.comt", structStatusImagesMain: "error", structServerStatusMain: "Error ")
]

Это конфигурации стола:

// table functions    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }

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

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

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

        let lblDescribtion : UILabel = cell.contentView.viewWithTag(6) as! UILabel
        let lblServerStatus : UILabel = cell.contentView.viewWithTag(8) as! UILabel
        let imgServer : UIImageView = cell.contentView.viewWithTag(7) as! UIImageView

                if myServerInfo .isEmpty {
                    print("myServerInfo is empty: ", myServerInfo)
                } else {
                    lblDescribtion.text = myServerInfo[indexPath.row].structHosts
                    imgServer.image = UIImage(named: myServerInfo[indexPath.row].structStatusImagesMain)
                    lblServerStatus.text  = myServerInfo[indexPath.row].structServerStatusMain
                }

        return cell
    }

person Jake2Finn    schedule 10.09.2018    source источник
comment
Начните с организации вашей модели данных в массив массивов, соответствующих тому, как вы хотите, чтобы она отображалась в табличном представлении.   -  person rmaddy    schedule 10.09.2018
comment
Вывод повторяется, потому что вы не учитываете свойство section объекта indexPath. Кстати: viewWithTag устарела на пару лет. Создайте пользовательскую ячейку в IB и используйте торговые точки.   -  person vadian    schedule 10.09.2018


Ответы (2)


Эти три строки:

lblDescribtion.text = myServerInfo[indexPath.row].structHosts
imgServer.image = UIImage(named: myServerInfo[indexPath.row].structStatusImagesMain)
lblServerStatus.text  = myServerInfo[indexPath.row].structServerStatusMain

В таблице есть 2 раздела, в каждом по 2 строки. Они сопоставляются с массивом из 4 элементов. Таким образом, index.section изменяется от 0 до 1, index.row также изменяется от 0 до 1, то есть всего 4, что соответствует длине массива.

Вам нужно сделать этот перевод правильно:

let index = indexPath.section * 2 + indexPath.row

lblDescribtion.text = myServerInfo[index].structHosts
imgServer.image = UIImage(named: myServerInfo[index].structStatusImagesMain)
lblServerStatus.text  = myServerInfo[index].structServerStatusMain

Однако одно предупреждение: то, как вы структурируете данные, создает много проблем, если вы хотите, чтобы в каждом разделе было разное количество строк.

person Code Different    schedule 10.09.2018

1) Сначала вам нужно создать структуру для данных раздела

Struct SectionData {
     Let title: String
     Let data: [serverData]

}

// structure for serverData type
struct serverData {
    var structHosts: String
    var structStatusImagesMain: String
    var structServerStatusMain: String
}

2) затем мы заполняем данные для каждого заголовка раздела

    // data filled in my array "section" and in my array "myServerInfo" of type serverData    

let myServerInfo = [SectionData]()
Let section1 = SectionData(title: "section1", data: 
    serverData(structHosts: "www.google.com", structStatusImagesMain: "error", structServerStatusMain: "Error "), 
    serverData(structHosts: "www.amazon.com", structStatusImagesMain: "error", structServerStatusMain: "Error "))

Let section2 = SectionData(title: "section2", data: 
    serverData(structHosts: "www.ebay.com", structStatusImagesMain: "error", structServerStatusMain: "Error "), 
    serverData(structHosts: "www.apple.comt", structStatusImagesMain: "error", structServerStatusMain: "Error "))

myServerInfo.append(section1)
myServerInfo.append(section2)

3) таблица конфигурации

// table functions    
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return myServerInfi[section].title
}

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myServerInfo[section].data.count
}

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

    let lblDescribtion : UILabel = cell.contentView.viewWithTag(6) as! UILabel
    let lblServerStatus : UILabel = cell.contentView.viewWithTag(8) as! UILabel
    let imgServer : UIImageView = cell.contentView.viewWithTag(7) as! UIImageView

            if myServerInfo .isEmpty {
                print("myServerInfo is empty: ", myServerInfo)
            } else {
                lblDescribtion.text = myServerInfo[indexPath.section][indexPath.row].structHosts
                imgServer.image = UIImage(named: myServerInfo[indexPath.section][indexPath.row].structStatusImagesMain)
                lblServerStatus.text  = myServerInfo[indexPath.section][indexPath.row].structServerStatusMain
            }

    return cell
}
person Bola Ibrahim    schedule 10.09.2018