There aren't very many tutorials for this for Swift 5.1 and I am pretty novice. I am wondering how to make the tableView delete override func work for my code. It gives me an error on objects because they are an unresolved identifier. Also what would go in the insert?
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = posts[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = posts[indexPath.row].name
return cell!
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row) // Here I get an error because objects is an unresolved identifier.
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. I am also confused as to what goes here.
}
}
All of the information you will need can be found here.
This method allows the delegate to customize the editing style of the cell located atindexPath. If the delegate does not implement this method and the UITableViewCell object is editable (that is, it has its isEditing property set to true), the cell has the UITableViewCell.EditingStyle.delete style set for it.
This is what you are missing:
https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614869-tableview
override func tableView(_ tableView: UITableView,
editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
Here you are using an object to remove data for the index path which is wrong you are using "posts" named array to show values on the table view. So, this "posts" array contains objects which are visible on the table view.
So, here when you want to remove object then this means you have to remove objects from the "posts" array. Below the attached function with some changes, you can check this it will work for you.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
posts.remove(at: indexPath.row) // Here I get an error because objects is an unresolved identifier.
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
posts.append("Here insert what you want") //inside append you can append/insert values to the array
tableView.reloadData()
}
}
Related
for UITableViews I have added three difference cells
How to Enable delete option for specific cell
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
switch dataSource[indexpath.section].menu {
case "Attachment":
if editingStyle == AttachmentTableViewCell.EditingStyle.delete {
attachmentList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}
break
default:
break
}
}
In this case it's shows Delete option for other cell too.
How to stop showing the Delete option on swipe to other UITableViewCell.
Implement tableView(_:editingStyleForRowAt:) and return none for the index paths which should not show the delete option.
This worked for me.
Overriding this func from UITableViewController
or implementing it UITableViewDelegate
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
The indexpaths were you want an action return a UISwipeActionsConfiguration else return nil.
like this
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// return nil on specific rows
guard indexPath.row != 1 else {
return nil
}
let contexualAction = UIContextualAction(style: .normal, title: "Action") { _, _, _ in
// Do Action
}
let swipeAction = UISwipeActionsConfiguration(actions: [contexualAction])
return swipeAction
}
I am using JSON to parse data from Spotify and add songs into a UITableView. The songs play fine, and I added functionality for deleting cells, but when adding functionality for reording cells, I can''t play songs and I can't swipe to delete them either. Any ideas would be appreciated.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.isEditing = true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
This adds the album image and song name to the TableView.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = posts[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = posts[indexPath.row].name
return cell!
}
This adds the swipe to delete functionality.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
posts.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
This adds the reordering functionality.
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = self.posts[sourceIndexPath.row]
posts.remove(at: sourceIndexPath.row)
posts.insert(movedObject, at: destinationIndexPath.row)
debugPrint("\(sourceIndexPath.row) => \(destinationIndexPath.row)")
self.tableView.reloadData()
}
You don't want to set
self.tableView.isEditing = true
in viewDidLoad. This takes you from the "normal" mode where you can select a cell, or other elements in a cell. Setting "self.tableview.isEditing" is the equivalent of hitting an edit button on the top right-hand corner of many tableViews.
How can i create info button on the right side for editing the content along with the deletion control(left side) whenever i click edit button?
(something like this)
`
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}`
Use accessoryType.
In cellForRowAt method, add
cell.editingAccessoryType = .detailButton
and Give action to it by
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
print("Accessory btn tapped")
}
I have got to the point where I can add cells that all have different labels. But, when the row is swiped to be deleted it will only delete the text associated with the cell and not the cell itself. I've tried to add SavedMessages.deleteRows(at: [indexPath], with: .automatic) inside the if statement but every time the app tries to delete the row, the app crashes.
Here is the code:-
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
if editingStyle == UITableViewCellEditingStyle.delete {
let delete: NSFetchRequest<Messages> = Messages.fetchRequest()
do {
var deleteMessage = try
PersistenceServce.context.fetch(delete)
PersistenceServce.context.delete(messages.remove(at: indexPath.row))
PersistenceServce.saveContext()
self.messages = deleteMessage
SavedMessages.reloadData()
} catch {}
}
}
Thanks in advance!
Maybe you are not using
tableView.cellForRow(at: indexPath)?.removeFromSuperview()
I created an example where removing data as well as the cell is getting removed perfectly fine.
var data = [1,2,3,4,5]
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int
{
return data.count
}
override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
data.remove(at: indexPath.row) //removing the value from data source.
tableView.cellForRow(at: indexPath)?.removeFromSuperview() //removing the cell
tableView.reloadData() //reloading Table data.
}
}
This should be trivial but I can't get it working.
I want to move a row in a UITableView in a NSFetchedResultsControllerDelegate.
I can easily delete rows, but inserting doesn't seem to work (NSInternalInconsistencyException).
I am trying
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationindex = IndexPath(item: 0, section: 0)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.insertRows(at: [destinationindex], with: .fade)
}
I have also tried
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let delobject = fetchedResultsController?.object(at: indexPath)
fetchedResultsController?.managedObjectContext.delete(delobject!)
fetchedResultsController?.managedObjectContext.insert(delobject!)
}
Of course a simple delete works; for example swipe to delete:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if (indexPath.row != 0) {
let delobject = fetchedResultsController?.object(at: indexPath)
fetchedResultsController?.managedObjectContext.delete(delobject!)
}
}
}
Your data model must fit the tableView so number of items in data equals number of rows in tableView.
A FetchedResultsController based TableView reflects the results of a CoreData fetch request. Inserting a row in the UITableView means inserting a new entry in CoreData.
And that is what you want to do: Create a new entry in Core Data (Like you do already do when deleting a row).