I want to delete a UITableView
row on a uibutton action in swift.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
What you need to do is pretty much this :
func myButtonMethod(sender : UIButton!) {
self.dataSource.removeAtIndex(myIndex) // dataSource being your dataSource array
self.tableview!.reloadData()
// you can also call this method if you want to reduce the load, will also allow you to choose an animation
//self.tableView!.deleteRowsAtIndexPaths([NSIndexPath(forItem: myIndex, inSection: 0)], withRowAnimation: nil)
}
add a method like this as target of your button :
self.myButton.addTarget(self, action: "myButtonMethod:", forControlEvents: .TouchUpInside)
回答2:
You can do it like:
@IBAction func removeCell() {
self.dataSource.removeAtIndex(index) // this is the dataSource array of your tableView
tableView.deleteRowsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)], withRowAnimation: .Left)
}
Connect this IBAction
to touchUpInside
action of your button. Make sure you remove the element from your data source first and then you can remove it from your table view.
If you don't want to animate the removal of your row you can simple replace that line of code with tableView.reloadData()
回答3:
Try this also:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
rowIndex = indexPath.row // declare a global variable
}
@IBAction func reomveButton(_ sender: Any)
{
self.array.remove(at: rowIndex)
TableView.reloadData()
}
回答4:
Little explanation... For Swift 4, Swift 5... First declare class variable:
var indexForCell = Int()
Then make IBAction for removal of row:
@IBAction func removeRow(_ sender: Any) {
self.modelArray.remove(at: indexForCell)
myTableView.reloadData()
}
Change default value of index variable to match indexPath:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
indexForCell = indexPath.row
}
Finally, add action to your reusable cell button:
myRemoveButton.addTarget(self, action: #selector(self.removeRow), for: .touchDown)
This will remove every instance of a row with myRemoveButton.