Aggiorna determinate righe di UITableView in base a Int in Swift


88

Sono uno sviluppatore principiante in Swift e sto creando un'app di base che include un UITableView. Voglio aggiornare una certa riga della tabella usando:

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

e voglio che la riga che verrà aggiornata provenga da un Int denominato rowNumber

Il problema è che non so come farlo e tutti i thread che ho cercato sono per Obj-C

Qualche idea?


C'è solo una sezione?
— Lyndsey Scott,

Risposte:


195

Puoi creare un NSIndexPathutilizzando la riga e il numero di sezione, quindi ricaricarlo in questo modo:

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

In questo esempio, ho ipotizzato che la tua tabella abbia solo una sezione (cioè 0) ma puoi modificare quel valore di conseguenza.

Aggiornamento per Swift 3.0:

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

se per una particolare sezione il numero di righe verrà modificato allora? @Lyndsey Scott
— tuffo il

@Lyndsey: In realtà all'inizio diciamo che ho 2 celle in quella sezione di cui sto per ricaricare, dopo aver ricaricato diciamo che avrò un numero (x) di celle in quella particolare sezione, quindi la mia domanda è quella in linea di calcolo indexpath, sono sicuro della sezione ma sono confuso sul numero di righe, perché si blocca al cambio del numero di righe var indexPath = NSIndexPath (forRow: rowNumber, inSection: 0)
— dip

@dip devi guardare il tuo tableView: numberOfRowsInSection: algoritmo del metodo per ottenere quelle informazioni ... Ti consiglio di pubblicare la tua domanda sul forum poiché sembra un problema specifico che stai riscontrando con il tuo codice ...
— Lyndsey Scott

Dove chiamare questo metodo?
— Master AgentX,

22

Per una soluzione di animazione a impatto morbido:

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)

Questo è un altro modo per proteggere l'app dall'arresto anomalo:

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)
   }
}

4

Swift 4

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

2

In 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)

Per impostazione predefinita, se hai solo una sezione in TableView, puoi inserire il valore di sezione 0.


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

1
Ciao, benvenuto in Stack Overflow e grazie per la tua prima risposta. Per rendere la risposta più utile ad altre persone, è buona norma annotare la risposta con un testo che spieghi perché affronta la domanda originale del PO.
— 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

Inoltre, se hai sezioni per tableview, non dovresti provare a trovare tutte le righe che vuoi aggiornare, dovresti usare le sezioni di ricarica. È un processo facile e più equilibrato:

yourTableView.reloadSections(IndexSet, with: UITableViewRowAnimation)

0

Che ne dite di:

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

0

Swift 4.1

usalo quando elimini una riga usando selectedTag of row.

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

Mi rendo conto che questa domanda è per Swift, ma qui c'è il codice Xamarin equivalente della risposta accettata se qualcuno è interessato.

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()

Mi sono trovato in una situazione particolare. Il mio obiettivo principale era raggiungere questo obiettivo quando l'utente si trova in una cella. E ho apportato alcune modifiche. Puoi aggiornare solo la cella, è dentro, senza caricare l'intera tabella e confondere l'utente. Per questo motivo, questa funzione sfrutta le proprietà tableView, aggiungendo un ReloadDataCell personalizzato. E aggiungendo tableview.reloadDataSavingSelecctions (). Dove, fai qualche azione. E una volta che l'ho fatto, volevo condividere quella soluzione con te.
— irwin B

Per favore aggiungi tutti i chiarimenti alla tua risposta modificandola
— Nico Haase
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.