Deleting a Row from a UITableView in Swift?
Works for Swift 3 and Swift 4
Use the UITableViewDataSource tableView(:commit:forRowAt:)
method, see also this answer here:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")
self.catNames.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
Delete rows from tableview using swift
To define "[indexPath]". It becomes [IndexPath(row: indexPath.row, section: 0)]
tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .automatic)
or
recall the particular section in the table view also
This will work outside of the function
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
UITableView Delete Row
This is because your numberOfRowsInSection
data source implementation always returns 1 (fixed).
Typically, you store objects in an array, which defines the number of rows. And, commitEditingStyle
should remove the object from the array and then delete the row.
– (void)tableView: (UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath: (NSIndexPath *)indexPath {if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[maTheData removeObjectAtIndex:[indexPath row]];
// Delete row using the cool literal version of [NSArray arrayWithObject:indexPath]
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
Follow this link for more details.
How do I delete rows from a tableview in the context of a core data one to many relationship? (Swift)
I solved the issue:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
let itemsOnListArray = myFetchRCTripName!.itineraries?.allObjects
let obj = itemsOnListArray?[indexPath.row] as! Itinerary
myFetchRCTripName!.removeFromItineraries(obj)
tableView.deleteRows(at: [indexPath], with: .automatic)
CoreDataStack.shared.saveContext()
}
}
How to delete rows from UITableView and update array from UserDefaults in Swift / iOS
You are trying to operate on non-property list object.
You have to follow below mentioned steps:
Parse your cart data from UserDefaults according to "[CartStruct]"
Check and delete It.
Update after deletion to UserDefaults
Reload your TableView
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
cartArray = self.updateCartItems(name: cartArray[indexPath.row].cartItems.name)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
Here, You need to check and delete:
func updateCartItems(name: String) -> [CartStruct] {
guard var cartItems = self.getCartData() else { return [] }
cartItems = cartItems.filter({ $0.cartItems.name != name })
if let updatedCart = try? PropertyListEncoder().encode(cartItems) {
UserDefaults.standard.set(updatedCart, forKey: "cartt")
}
UserDefaults.standard.set(cartItems.count, forKey: "CountAddedProducts")
return cartItems
}
Deleting the bottom row of TableView
Edit 2
After some experimentation, it appears to be an issue with iOS 12
(at least, on my iOS 12.4
simulator and device).
This can be (somewhat) confirmed by
- launch the default iPhone Reminders app
- add a bunch of reminders (I just used A, B, C, etc...) so you have enough that scrolling is needed
- scroll down to the last row
- delete the last row
You'll see that the row deletion animation is faulty. In fact, deleting any row does not provide the smooth animation we see in iOS 13
.
Doing some searching I find similar issues back with iOS 7
reportedly fixed in iOS 8+
... so perhaps the same bug returned in one of the iOS 12
versions. You may be able to use one of those older work-arounds, but based on comments it was pretty hit-or-miss.
I still stand by my initial comment, though, that there is no reason for:
tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
to be called after the row deletion.
Original Answer
It sounds like you are doing too much...
This is all you should need to get the row to delete and the other rows to "slide down":
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
Results.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
No need to reload the data.
See example here: https://imgur.com/a/JvDQ1P6
Edit
Here is a complete (very simple) example. No @IBOutlet
or @IBAction
connections... just add a new table view controller to your Storyboard and assign its custom class to SampleTableViewController
:
class SampleCell: UITableViewCell {
let testView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .blue
return v
}()
let testLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
return v
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
@objc
func commonInit() -> Void {
contentView.addSubview(testView)
contentView.addSubview(testLabel)
let g = contentView.layoutMarginsGuide
// avoid constraint warnings
let c = testView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0)
c.priority = UILayoutPriority(rawValue: 999)
NSLayoutConstraint.activate([
c,
testView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
testView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
testView.heightAnchor.constraint(equalToConstant: 50.0),
testView.widthAnchor.constraint(equalTo: testView.heightAnchor),
testLabel.leadingAnchor.constraint(equalTo: testView.trailingAnchor, constant: 12.0),
testLabel.centerYAnchor.constraint(equalTo: testView.centerYAnchor),
testLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
])
}
}
class SampleTableViewController: UITableViewController {
var data: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
// fill data array with 30 strings
data = (1...30).map { "This is row \($0)" }
tableView.register(SampleCell.self, forCellReuseIdentifier: "SampleCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath) as! SampleCell
c.testLabel.text = data[indexPath.row]
return c
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
data.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
Related Topics
How to Stop an Infinitely Rotating Image? and How Does One Implement Removeallanimations
How to Integrate Mapbox Sdk with Swiftui
Calling a Child Inside 2 Levels of Nodes
Code Only Retrieving One Value from Data in Firebase
Does _Arraytype or _Arrayprotocol Not Available in Swift 3.1
Ambiguous Method Overload with Closures in Swift, But Only When Closure Returns a Value
Prepare for Segue with Array - Xcode 8.0 Swift 3.0
Swift Generic Func Cannot Convert Value of Type to Expected Argument Type
Stateobject as Parameter for Another Object in Init()
How Assistant Model Works in Swift
Passing Unknown Number of Arguments in a Function
Swift: How to Get Information for an Application Which Is Not Running
Disable Email Detection in Swiftui's Text
Swift Why Isn't My Date Object That's (Equatable) Equal After Converting It to a String and Back
How to Increment Exponentially in Swift
How to Properly Test Against Certain Values in Nseventmodifierflags via Swift