Atualizar determinada linha de UITableView com base em Int em Swift


90

Sou um desenvolvedor iniciante em Swift e estou criando um aplicativo básico que inclui um UITableView. Quero atualizar uma determinada linha da tabela usando:

self.tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.none)

e eu quero que a linha que será atualizada seja de um Int chamado rowNumber

O problema é que não sei como fazer isso e todos os tópicos que pesquisei são para Obj-C

Alguma ideia?


Existe apenas uma seção?
— Lyndsey Scott

Respostas:


198

Você pode criar um NSIndexPathusando o número da linha e da seção e recarregá-lo assim:

let indexPath = NSIndexPath(forRow: rowNumber, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)

Neste exemplo, presumi que sua tabela tem apenas uma seção (ou seja, 0), mas você pode alterar esse valor de acordo.

Atualização para Swift 3.0:

let indexPath = IndexPath(item: rowNumber, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)

se, para uma seção específica, o número de linhas for alterado? @Lyndsey Scott
— mergulho em

@Lyndsey: Na verdade, a princípio, digamos que eu tenha 2 células naquela seção da qual vou recarregar, depois de recarregar, digamos que terei qualquer (x) número de células nessa seção específica, então minha pergunta é aquela na linha de cálculo do indexpath, tenho certeza sobre a seção, mas estou confuso quanto ao número de linhas, porque ele está travando na alteração do número de linhas var indexPath = NSIndexPath (forRow: rowNumber, inSection: 0)
— mergulho

@dip, você precisa olhar para sua tableView: numberOfRowsInSection: algoritmo do método para obter essa informação ... Eu recomendo postar sua pergunta no fórum, pois parece que você está tendo um problema específico com seu código ...
— Lyndsey Scott

Onde chamar esse método?
— Master AgentX

22

Para uma solução de animação de impacto suave:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

Esta é outra maneira de proteger o aplicativo contra falhas:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
    if visibleIndexPaths != NSNotFound {
        tableView.reloadRows(at: [indexPath], with: .fade)
    }
}

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
   if visibleIndexPaths != NSNotFound {
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
   }
}

3

Em Swift 3.0

let rowNumber: Int = 2
let sectionNumber: Int = 0

let indexPath = IndexPath(item: rowNumber, section: sectionNumber)

self.tableView.reloadRows(at: [indexPath], with: .automatic)

byDefault, se você tem apenas uma seção em TableView, então você pode colocar o valor de seção 0.


3

Swift 4

let indexPathRow:Int = 0    
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

Por que você copia e cola minha resposta?
— Hardik Thakkar

2
let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

1
Olá, bem-vindo ao Stack Overflow e obrigado por sua primeira resposta. Para tornar a resposta mais útil para outras pessoas, é uma prática recomendada anotar sua resposta com um texto que explique por que ela aborda a pergunta original do OP.
— Spangen

2

SWIFT 4.2

    func reloadYourRows(name: <anyname>) {
    let row = <your array name>.index(of: <name passing in>)
    let reloadPath = IndexPath(row: row!, section: 0)
    tableView.reloadRows(at: [reloadPath], with: .middle)
    }

1

Além disso, se você tiver seções para tableview, você não deve tentar encontrar todas as linhas que deseja atualizar, você deve usar reload seções. É um processo fácil e mais equilibrado:

yourTableView.reloadSections(IndexSet, with: UITableViewRowAnimation)

0

E se:

self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)

0

Swift 4.1

use-o ao deletar linha usando selectedTag de linha

self.tableView.beginUpdates()

        self.yourArray.remove(at:  self.selectedTag)
        print(self.allGroups)

        let indexPath = NSIndexPath.init(row:  self.selectedTag, section: 0)

        self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)

        self.tableView.endUpdates()

        self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)

0

Sei que esta pergunta é para Swift, mas aqui está o código equivalente Xamarin da resposta aceita se alguém estiver interessado.

var indexPath = NSIndexPath.FromRowSection(rowIndex, 0);
tableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Top);

0
    extension UITableView {
        /// Reloads a table view without losing track of what was selected.
        func reloadDataSavingSelections() {
            let selectedRows = indexPathsForSelectedRows

            reloadData()

            if let selectedRow = selectedRows {
                for indexPath in selectedRow {
                    selectRow(at: indexPath, animated: false, scrollPosition: .none)
                }
            }
        }
    }

tableView.reloadDataSavingSelections()

Eu me encontrei em uma situação particular. Meu principal objetivo era conseguir isso quando o usuário estava em uma célula. E fiz algumas modificações. Você pode atualizar apenas a célula, está dentro, sem carregar a tabela inteira e confundir o usuário. Por esse motivo, esta função aproveita as propriedades tableView, adicionando um ReloadDataCell personalizado. E adicionando tableview.reloadDataSavingSelecctions (). Onde, você faz alguma ação. E assim que o fiz, gostaria de compartilhar essa solução com você.
— irwin B

Adicione todos os esclarecimentos à sua resposta editando-a
— Nico Haase
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.