I have table view that delete some rows with following:
func deleteRows(_ indecies: [Int]) {
guard !indecies.isEmpty else { return }
let indexPathesToDelete: [IndexPath] = indecies.map{ IndexPath(row: $0, section: 0)}
let previousIndex = IndexPath(row: indecies.first! - 1, section: 0)
tableView.deleteRows(at: indexPathesToDelete, with: .none)
tableView.reloadRows(at: [previousIndex], with: .none)
}
In cellForRow i have cell that have "tap" closure like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.row < presenter.fields.count else { return EmptyCell() }
let field = presenter.fields[indexPath.row]
switch field.cellType {
case .simple:
guard let model = field as? SimpleTextItem else { return EmptyCell() }
let cell = SimpleTextCell()
cell.setup(label: LabelSL.regularSolidGray(), text: model.text, color: Theme.Color.bleakGray)
return cell
case .organization:
guard let model = field as? OrganizationFilterItem else { return EmptyCell() }
let cell = OrganizationFilterCell()
cell.setup(titleText: model.title,
holdingNumberText: model.holdingNumberText,
isChosed: model.isChosed,
isHolding: model.isHolding,
isChild: model.isChild,
bottomLineVisible: model.shouldDrawBottomLine)
cell.toggleControlTapped = {[weak self] in
self?.presenter.tappedItem(indexPath.row)
}
return cell
}
}
When
cell.toggleControlTapped = {[weak self] in
self?.presenter.tappedItem(indexPath.row)
}
Tapped after rows deletion, index is pass is wrong (it's old). For example, i have 10 rows, i delete 2-3-4-5 row, and then i tap on 2 row (it was 6 before deletion). That method pass "6" instead of "2".
Problem actually was solved by adding tableView.reloadData() in deleteRows function, but, as you may assume smoothly animation gone and it look rough and not nice. Why is table still pass old index and how to fix it?
A quite easy solution is to pass the cell in the closure to be able to get the actual index path
Delare it
var toggleControlTapped : ((UITableViewCell) -> Void)?
Call it
toggleControlTapped?(self)
Handle it
cell.toggleControlTapped = {[weak self] cell in
guard let actualIndexPath = self?.tableView.indexPath(for: cell) else { return }
self?.presenter.tappedItem(actualIndexPath.row)
}
Side note: Reuse cells. Creating cells with the default initializer is pretty bad practice.
Be sure to update your data too, indexes are appearing from numberofrows function of table view
Related
I have an app with an UITableView and its data gets updated regularly. If the data receives new element, the table view is reloaded. Let’s say the table view has place for 10 visible cells, but data for only 2 of them. The user has scrolled in either direction and not released the table view from touch. If the user has scrolled up, they may have hidden the first cell and only the second one would be visible. Then a new element is received and reloadData is called. Instead of waiting for releasing the table view to update, the tableview gets updated right away and the contentOffset is reset to 0. The tableView just resets to start position while the user has scrolled and not released.
I tried similar setup in separate Xcode project and the issue does not appear there. I wonder what the difference could be.
This is some of the code:
For the ViewController that is the dataSource:
func viewDidLoad() {
super.viewDidLoad()
//some other code
DataManager.shared.onElementReceival = { [weak self] in
guard let self = self else { return }
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataManager.shared.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.textColor = .white
cell.backgroundColor = .clear
if let name = DataManager.shared.data[indexPath.row].name {
cell.textLabel?.text = name
} else {
cell.textLabel?.text = "Unnamed"
}
return cell
}
From the DataManager
func didReceive(_ element: Element) {
data.append(element)
onElementReceival()
}
Try to reload only cell using:
tableview.insertRowsAtIndexPaths([IndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
In your example:
let onElementReceival:(IndexPath) -> Void = { [weak self] inx in
guard let self = self else { return }
DispatchQueue.main.async {
tablview.beginUpdates()
tablview.insertRowsAtIndexPaths(at: [inx], with: .automatic)
tablview.endUpdates()
}
}
From DataManager
func didReceive(_ element: Element) {
data.append(element)
onElementReceival(IndexPath(row:data.count, section: 0))
}
Code
Essentials for the problem parts of VC:
// Part of VC where cell is setting
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as Cell
let cellVM = viewModel.cellVM(for: indexPath)
cell.update(with: cellVM)
cell.handleDidChangeSelectionState = { [weak self] selected in
guard
let `self` = self
else { return }
self.viewModel.updateSelectionState(selected: selected, at: indexPath)
}
return cell
}
// Part of code where cell can be deleted
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "delete".localized, handler: { [weak self] _, indexPath in
guard let self = self else { return }
self.viewModel.delete(at: indexPath)
tableView.deleteRows(at: [indexPath], with: .left)
})
return [deleteAction]
}
Problem
When cell has been deleted and after that handleDidChangeSelectionState will be involved then indexPath passed into viewModel.updateSelectionState will be wrong (will be equal to value before cell deletion).
I think I know why
IndexPath is a struct so handleDidChangeSelectionState keeps copy of current value (not instance). Any update of original value will not update captured copy.
tableView.deleteRows will not reload datasource of tableview so cellForRowAt will not recall. It means handleDidChangeSelectionState will not capture updated copy.
My to approach to fix that problem
* 1st
Ask about indexPath value inside handleDidChangeSelectionState:
cell.handleDidChangeSelectionState = { [weak self, weak cell] selected in
guard
let `self` = self,
let cell = cell,
// now I have a correct value
let indexPath = tableView.indexPath(for: cell)
else { return }
self.viewModel.updateSelectionState(selected: selected, at: indexPath)
}
* 2nd
After every deletion perform reloadData():
let deleteAction = UITableViewRowAction(style: .destructive, title: "delete".localized, handler: { [weak self] _, indexPath in
guard let self = self else { return }
self.viewModel.delete(at: indexPath)
tableView.deleteRows(at: [indexPath], with: .left)
// force to recall `cellForRowAt` then `handleDidChangeSelectionState` will capture correct value
tableView.reloadData()
})
Question
Which approach is better?
I want to:
keep smooth animations (thanks to tableView.deleteRows(at: [])
find the better performance (I not sure which is more optimal, reloadData() or indexPath(for cell:))
Maybe there is a better 3rd approach.
Thanks for any advice.
Only the 1st approach fulfills the first condition to keep smooth animations. Calling reloadData right after deleteRows breaks the animation.
And calling indexPath(for: cell) is certainly less expensive than reloading the entire table view.
Don't use reload specific row, because the index has changed when you delete row, and it will remove animation after deleting row that's why you need to reload tableview.reloadData() it is a better option in your case.
let deleteAction = UITableViewRowAction(style: .destructive, title: "delete".localized, handler: { [weak self] _, indexPath in
guard let self = self else { return }
self.viewModel.delete(at: indexPath)
tableView.deleteRows(at: [indexPath], with: .left)
// force to recall `cellForRowAt` then `handleDidChangeSelectionState` will capture correct value
tableView.reloadData()
})
I have a collection view inside a table view cell at row = 1, that is loaded with content from Firebase Database after the cell is already dequeued. Therefore, using AutoDimensions on the cell at heightForRowAt: doesn't work since at that time, there is no content within the collection view. The collection view is anchored to all sides of the cell. What's the best way of updating the table view cell height at that specific index path when the collection view has loaded all of the data. Thanks!
In the VC containing the table view, I've set up a func retrieving a list of users from the DB that is called in viewDidLoad(), and I've set up protocols to reload the collectionView that is located in the tableView cell class.
fileprivate func retrieveListOfUsers() {
print ("fetching users from database")
let ref = Database.database().reference()
guard let conversationId = conversation?.conversationId else {return}
ref.child("conversation_users").child(conversationId).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionaries = snapshot.value as? [String:AnyObject] else {return}
for (key, _) in dictionaries {
let userId = key
Database.fetchUsersWithUID(uid: userId, completion: { (user) in
self.users.append(user)
DispatchQueue.main.async {
self.reloadDelegate.reloadCollectionView()
}
})
}
}, withCancel: nil)
}
This is the code for dequeuing the cell. I've removed the code for the first cell in this post since it's irrelevant and didn't want to make you read the unnecessary code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Code for cell in indexPath.row = 0
if indexPath.row == 1 {
let usersCell = tableView.dequeueReusableCell(withIdentifier: usersCellId, for: indexPath) as! UsersTableViewCell
usersCell.backgroundColor = .clear
usersCell.selectionStyle = .none
usersCell.collectionView.delegate = self
usersCell.collectionView.dataSource = self
self.reloadDelegate = usersCell
usersCell.users = users
return usersCell
}
}
If I return UITableView.automaticDimension the collection view doesn't show. It only shows if I set the func to return a constant like 200. I've set estimatedRowHeight and rowHeight in viewDidLoad().
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return UITableView.automaticDimension
}
return UITableView.automaticDimension
}
After you load the data source for the collection view, you can update specific rows in your table like this:
UIView.performWithoutAnimation {
tableView.reloadRows(at: [indexPath], with: .none)
}
For the row height - try to remove the method implementation, it should be enough if you already set a value for estimatedRowHeight.
I'm using a UIViewController with a UITableView connected to another UIViewController where I intend to be able to add entries from. They are linked through an unwind segue, but whenever I try to actually add an entry, I get this:
attempt to insert row 0 into section 0, but there are only 0 rows in
section 0 after the update
This is what I have:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch(segue.identifier ?? "") {
case "AddItem":
os_log("Adding a new item.", log: OSLog.default, type: .debug)
case "ShowDetail":
guard let DetailViewController = segue.destination as? ViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
guard let selectedCell = sender as? TableViewCell else {
fatalError("Unexpected sender: \(sender)")
}
guard let indexPath = tableView.indexPath(for: selectedCell) else {
fatalError("The selected cell is not being displayed by the table")
}
let selectedItem = items[indexPath.row]
DetailViewController.item = selectedItem
default:
fatalError("Unexpected Segue Identifier; \(segue.identifier)")
}
}
and
#IBAction func unwindToList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ViewController, let item = sourceViewController.item {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
items[selectedIndexPath.row] = item
self.tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
items.append(item)
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: items.count - 1, section: 0)], with: .automatic)
self.tableView.endUpdates()
}
}
}
and
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
and
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "TableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TableViewCell else {
fatalError("The dequeued cell is not an instance of TableViewCell")
}
let item = items[indexPath.row]
cell.labelName.text = item.name
return cell
}
How can this be fixed?
And forgive me, I am fairly new to Swift. :)
If you want to use insertRowsAtIndexPaths:withRowAnimation: you need to do it inside a beginUpdates and endUpdates block, after updating your data array. According to Documentation:
To insert and delete a group of rows and sections in a table view, first prepare the array (or arrays) that are the source of data for the sections and rows. After rows and sections are deleted and inserted, the resulting rows and sections are populated from this data store.
You are doing correctly by changing the array before calling insertRowsAtIndexPaths:withRowAnimation: but you need to use batch updates instead of reloadData.
There is a complete example at the Documentation link that you can check.
Make sure the TableView's dataSource is connected (when using a storyboard or nib) or assigned programmatically. These errors also arise when trying to update a TableView or CollectionView with no dataSource assigned.
I'm working on a basic list workout app right now that keeps track of workouts and then the exercises for each workout. I want to extend the current 'editing' mode of a TableViewController to allow for more advanced editing options. Here is what I have so far:
As you can see, I am inserting a section at the top of the table view so that the title of the workout can be edited. The problem I am facing is twofold:
There is no animation when the edit button is tapped anymore.
When you try to swipe right on one of the exercises (Squat or Bench press) the entire section containing exercises disappears.
I start by triggering one of two different functions on the setEditing function, to either switch to read mode or edit mode based on whether the boolean editing returns true or false.
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: true)
tableView.setEditing(editing, animated: true)
if editing {
switchToEditMode()
} else {
switchToReadMode()
}
}
Then I either insert the "addTitle" section (the text field seen in the second image) to an array called tableSectionsKey which I use to determine how to display the table (seen further below), and then reload the table data.
func switchToEditMode(){
tableSectionsKey.insert("addTitle", at:0)
self.tableView.reloadData()
}
func switchToReadMode(){
tableSectionsKey.remove(at: 0)
self.tableView.reloadData()
}
Here is my tableView data method. Basically the gist of it is that I have the array called tableSectionsKey I mentioned above, and I add strings that relate to sections based on what mode I'm in and what information should be displayed. Initially it just has "addExercise", which related to the "Add exercise to routine" cell
class WorkoutRoutineTableViewController: UITableViewController, UITextFieldDelegate, UINavigationControllerDelegate {
var tableSectionsKey = ["addExercise"]
}
Then in viewDidLoad I add the "exercise" section (for list of exercises) if the current workout routine has any, and I add the addTitle section if it's in new mode, which is used to determine if the view controller is being accessed from an add new workout button or a from a list of preexisting workouts (so to determine if the page is being used to create a workout or update an existing one)
override func viewDidLoad() {
super.viewDidLoad()
if workoutRoutine.exercises.count > 0 {
tableSectionsKey.insert("exercise", at:0)
}
if mode == "new" {
tableSectionsKey.insert("addTitle", at: 0)
}
}
Then in the cellForRowAt function I determine how to style the cell based on how the section of the table relates with an index in the tableSectionsKey array
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = indexPath.section
let sectionKey = tableSectionsKey[section]
let cellIdentifier = sectionKey + "TableViewCell"
switch sectionKey {
case "addTitle":
guard let addTitleCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AddTitleTableViewCell else {
fatalError("Was expecting cell of type AddTitleTableViewCell.")
}
setUpAddTitleTableViewCell(for: addTitleCell)
return addTitleCell
case "exercise":
guard let exerciseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ExerciseTableViewCell else {
fatalError("Was expecting cell of type ExerciseTableViewCell.")
}
let exercise = workoutRoutine.exercises[indexPath.row]
setUpExerciseTableViewCell(for: exerciseCell, with: exercise)
return exerciseCell
case "addExercise":
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
return cell
default:
fatalError("Couldn't find section: \(section), in WorkoutRoutineTableView" )
}
}
private func setUpExerciseTableViewCell(for cell: ExerciseTableViewCell, with exercise: Exercise) {
let titleText = exercise.name
let detailsText = "\(exercise.sets)x\(exercise.reps) - \(exercise.weight)lbs"
cell.titleLabel.text = titleText
cell.detailsLabel.text = detailsText
}
private func setUpAddTitleTableViewCell(for cell: AddTitleTableViewCell) {
cell.titleTextField.delegate = self
if (workoutRoutine.title != nil) {
cell.titleTextField.text = workoutRoutine.title
}
// Set the WorkoutRoutineTableViewController property 'titleTextField' to the 'titleTextField' found in the addTitleTableViewCell
self.titleTextField = cell.titleTextField
}
This isn't all of my code but I believe it is all of the code that could be relevant to this problem.
Your animation issue is due to the use of reloadData. You need to replace the uses of reloadData with calls to insert or delete just the one section.
func switchToEditMode(){
tableSectionsKey.insert("addTitle", at:0)
let section = IndexSet(integer: 0)
self.tableView.insertSections(section, with: .left) // use whatever animation you want
}
func switchToReadMode(){
tableSectionsKey.remove(at: 0)
let section = IndexSet(integer: 0)
self.tableView.deleteSections(section, with: .left) // use whatever animation you want
}