Crist
Crist

Reputation: 41

Reload tableview without scroll

I am new to swift I want to reload my tableview so I used tableviewName.reloadData() After this the table view is reloaded and scrolled a bit upwards but I want to stay where it is

Here is the code

func searchResult(row: Int, searchText: String, tag: Int) {

(defaultAnswerQuestionsArray[tag] as! DefaultAnswerObjectClass).defaultAnswerId = row

    (defaultAnswerQuestionsArray[tag] as! DefaultAnswerObjectClass).defaultAnswerDescription = searchText
    tableViewCollection.reloadData()
    tableViewCollection.alwaysBounceVertical = false
}

Upvotes: 1

Views: 1074

Answers (2)

mahan
mahan

Reputation: 14935

You need to set the content offset of the table-view using setContentOffset after reload.

func searchResult(row: Int, searchText: String, tag: Int) {

(defaultAnswerQuestionsArray[tag] as! DefaultAnswerObjectClass).defaultAnswerId = row

    (defaultAnswerQuestionsArray[tag] as! DefaultAnswerObjectClass).defaultAnswerDescription = searchText
    tableViewCollection.reloadData()
    tableViewCollection.alwaysBounceVertical = false
     
    /* NEW */
    let contentOffset = tableViewCollection.contentOffset
    tableViewCollection.layoutIfNeeded() 
    tableViewCollection.setContentOffset(contentOffset, animated: false)
}

Upvotes: 1

Victor Morei
Victor Morei

Reputation: 199

You can reload just visible cells like this:

let indexPaths = tableView.visibleCells.map { tableView.indexPath(for: $0) }.compactMap { $0 }
tableView.reloadRows(at: indexPaths, with: .automatic)

Upvotes: 1

Related Questions