I am making a table view and I want to make a function where you can delete a row by swiping right and tapping the delete button. Me and my teacher have tried for about half an hour to fix this problem but nothing seems to work.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var StoredValues = Values()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {//
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "meunSegue", sender: self)
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
_ = segue.destination as! SecondViewController
}
}
func tableView->(UITableView *)tableView canEditRowsAtIndexPath:(NSIndexPath *)indexPath {
return YES
}
- (void)tableView:(UITableView *)tableView committEditStyle: (UITableViewCellEditingStyle)
func tableView {
var cell = UITableView.self
var Animation = UITableViewRowAnimation(rawValue: 1)
if editingStyle == UITableViewCellEditingStyle.delete {
cell.deleteRows(indexPath)
//cell.deleteRows(at: [NSIndexPath], with: UITableViewRowAnimation.automatic)
}
}
class SecondViewController: UIViewController {
var recievedData = ""
override func viewDidLoad() {
super.viewDidLoad()
print(recievedData)
}
}
}
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.
This swift function can delete a row by swiping right and tapping the delete button. Actually this function delete item from items array then delete row. In addition this row removed from tableView.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
// your items include cell variables
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
来源:https://stackoverflow.com/questions/43744911/uitableview-delete-row