Just implement this function in your UIViewController
func tableView(_ tableView: UITableView, commit editingStyle:UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
myArray.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
}
else if editingStyle == .insert {
// no need to implement
}
}
Complete Source for UIViewController
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//my sample data for table view
private var myArray: [String] = [
"This is Row# 1",
"This is Row# 2",
"This is Row# 3",
"This is Row# 4"]
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Main View"
myTableView = UITableView()
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
myTableView.translatesAutoresizingMaskIntoConstraints = false
//myTableView.isEditing = true
self.view.addSubview(myTableView)
//hide empty rows at the bottom
myTableView.tableFooterView = UIView()
//auto layout for the table view
let views = ["view": view!, "tableView" : myTableView]
var allConstraints: [NSLayoutConstraint] = []
allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
"V:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
"H:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
NSLayoutConstraint.activate(allConstraints)
}
//when you tap on the row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
//how many rows in the section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
-> Int {
return myArray.count
}
//paint the row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell",
for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
myArray.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
} else if editingStyle == .insert {
// no need to implement
}
}
}
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.