Массив не удаляет элементы правильно Swift 4 - PullRequest
0 голосов
/ 05 июня 2018

В моем приложении я использую tableView, чтобы продемонстрировать варианты того, куда идти на свидание.Для этого у меня есть пара groups и subgroups.

Группы и подгруппы:

var mainGroups : [String] = ["Out On The Town", "Night In"]
let subGroups : [String] = ["Restaurants", "Activities", "Laid Back"]
let restaurantSubGroups : [String] = ["Dining", "Fast Food", "Desserts"]

Таким образом, если щелкнуть ячейку Restaurant, она добавит mainGroup, создаст ячейки со строками restaurantSubGroup внизу, и еслипри повторном нажатии все эти ячейки будут удалены.

Для удаления я проверяю, была ли ячейка нажата ранее.Если это так, я удаляю строки restaurantSubGroups из mainGroup и соответственно обновляю ячейки.Довольно просто, верно?

Проблема возникает с массивом.По причине, которую я не могу найти, он удаляет dining и desserts из массива, но пропускает Fast Food и вместо этого удаляет Laid Back.

Вот код:

//Bools declared as class variables
var outOnTheTownIsActive : Bool = false
var restaurantIsActive : Bool = false

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
    cell.textLabel?.text = "\(mainGroups[indexPath.row])"

    if mainGroups.contains((cell.textLabel?.text)!) {
        cell.textLabel?.textAlignment = .left
    }
    if subGroups.contains((cell.textLabel?.text)!) {
        cell.textLabel?.textAlignment = .center
    }
    if restaurantSubGroups.contains((cell.textLabel?.text)!) || activitySubGroups.contains((cell.textLabel?.text)!) || laidbackSubGroups.contains((cell.textLabel?.text)!) {
        cell.textLabel?.textAlignment = .right
    }
    cell.selectionStyle = .none
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    let cellText = cell?.textLabel?.text

    switch cellText {
    case "Out On The Town":
        print("\(String(describing: cell?.textLabel?.text)) is clicked and row is \(indexPath.row)")
        if outOnTheTownIsActive {
            alterArray(starting: 2, ending: 4)
            addDeleteCells(starting: 1, ending: 3, indexPath: indexPath, add: false)
            outOnTheTownIsActive = false
        } else {
            mainGroups.insert(contentsOf: subGroups, at: indexPath.row+1)
            addDeleteCells(starting: 1, ending: 3, indexPath: indexPath, add: true)
            outOnTheTownIsActive = true
        }

    case "Restaurants":
       // print("\(String(describing: cell?.textLabel?.text)) is clicked and row is \(indexPath.row)")
        if restaurantIsActive {
            print("The items in the array are \(mainGroups) and i am removing \(mainGroups[2]), \(mainGroups[3]), and \(mainGroups[4])")
            alterArray(starting: 2, ending: 4)
            addDeleteCells(starting: 1, ending: 3, indexPath: indexPath, add: false)
            restaurantIsActive = false
            print("The new array is \(mainGroups)")
        } else {
            mainGroups.insert(contentsOf: restaurantSubGroups, at: indexPath.row+1)
            addDeleteCells(starting: 1, ending: 3, indexPath: indexPath, add: true)
            restaurantIsActive = true
        }

     //   print("There are \(mainGroups.count) in the array and they are \(mainGroups)")

    case "Dining":
        getAnnotations(query: "Restaurant", category: .restaurants, price: .twoDollarSigns)

    case "Fast Food":
        getAnnotations(query: "Fast Food", category: .food, price: nil)

    case "Desserts":
        getAnnotations(query: "Ice Cream", category: .food, price: nil)
}

func addDeleteCells(starting : Int, ending: Int, indexPath : IndexPath, add : Bool) {
    for i in starting...ending {
        let iPath = IndexPath(row: indexPath.row+i, section: 0)
        indexPaths.append(iPath)
    }
    if add {
        annotationTableView.beginUpdates()
        annotationTableView.insertRows(at: indexPaths, with: .automatic)
        annotationTableView.endUpdates()
    } else {
        annotationTableView.beginUpdates()
        annotationTableView.deleteRows(at: indexPaths, with: .automatic)
        annotationTableView.endUpdates()
    }
    indexPaths.removeAll()
}

func alterArray(starting: Int, ending : Int) {
    for i in starting...ending {
        print("In alterArray and removing \(mainGroups[i])")
        mainGroups.remove(at: i)
    }
}

, а вот распечатка консоли при нажатии на «Out of the Town» один раз, а затем «Restaurants» дважды:

The items in the array are ["Out On The Town", "Restaurants", "Dining", "Fast Food", "Desserts", "Activities", "Laid Back", "Night In"] and i am removing Dining, Fast Food, and Desserts
In alterArray and removing Dining
In alterArray and removing Desserts
In alterArray and removing Laid Back
The new array is ["Out On The Town", "Restaurants", "Fast Food", "Activities", "Night In"]

Любая идея относительно того, почему он пропустил бы Fast Food и удалил Laid Back?

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

1 Ответ

0 голосов
/ 05 июня 2018

Поскольку по окончании первого цикла индексы массива изменились

 mainGroups.remove(at: i)

, поэтому удаляемый элемент будет иметь низкий индекс (-1), чем тот, который должен быть удален,

endпервой петли Столовая удалена, поэтому эта

["Out On The Town", "Restaurants", "Dining",
"Fast Food", "Desserts", "Activities", "Laid Back", "Night In"]

будет (вы ожидаете Fast Food следующей)

["Out On The Town", "Restaurants", "Fast Food",
"Desserts", "Activities", "Laid Back", "Night In"]

, но индекс3 теперь содержит Десерты

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