Remove cell when button pressed inside cell CustomTableViewCell
Your immediate issue is the line:
delegate?.RadioTapped(sender.tag)
It should be:
delegate?.RadioTapped(tag)
Since it is the cell's tag being set.
But do not use tags for this. Update the cell's delegate method to pass itself as the parameter. Then the delegate can determine the cell's indexPath from the table view.
Updated protocol:
protocol TableViewCellDelegate {
func radioTapped(_ cell: TableViewCell)
}
Updated cell tap handler:
@IBAction func radioTapped(_ sender: UIView){
delegate?.radioTapped(self)
}
Updated cellForRowAt:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
let task = tasks[indexPath.row]
cell.delegate = self
Update delegate method in the table view:
func radioTapped(_ cell: TableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
print("Radio Tapped at \(indexPath)")
}
}
Swift 5 how to delete and copy tableview cell by using button
It deletes the first row in the first section in because you told the function to delete such an indexPath indexPath = IndexPath(item: 0, section: 0)
Second you need to save which indexPath to copy/delete when an indexPath is selected
In your view controller have a variable:
var SelectedIndexPath = IndexPath
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
SelectedIndexPath = indexPath
}
@IBAction func didTapDeleteBtn(_ sender: Any) {
print("didTapDeleteBtn")
YOUR_MODEL.remove(at: SelectedIndexPath.row)// if your model is just an array
tableView.deleteRows(at: [SelectedIndexPath], with: .fade)
//tableView.reloadData()// You normally do not need reloadData() if you use tableView.deleteRows
}
@IBAction func didTapCopyBtn(_ sender: Any) {
print("didTapCopyBtn")
dataAry.append[dataAry[SelectedIndexPath]]
tableView.reloadRows(at: SelectedIndexPath, with: .none)
}
delete tableview cell from button inside it
Instead of
var numberOfRows = 5
use an array
var arr = [0,1,2,3,4]
Then
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv
cell.lbl.text = "\(arr[indexPath.row])"
cell.deleteBTN.tag = indexPath.row
cell.deleteBTN.addTarget(self, action:#selector(delete(_:)), for: .touchUpInside)
return cell
}
@objc func handleRegister(_ sender: UIButton){
arr.remove(at:sender.tag)
tableView.deleteRows(at:[Indexpath(row:sender.tag,section:0)],with:.none)
}
delete tableviewcell from button within inside the cell
Here's my solution:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, CustomTvCellDelegate, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
var cellCount = 2
var tableview = UITableView()
var selectedIndexPath = IndexPath(row: 0, section: 0)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellCount // use a variable here so you can change it as you delete cells, else it will crash
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTv
cell.delegate = self
return cell
}
func deleteCell(_ customTV: CustomTv, location: CGPoint) {
// put the button location in an index path array
var deleteArray = [IndexPath]()
if let indexPath = tableview.indexPathForRow(at: location) {
deleteArray.append(indexPath)
}
cellCount -= 1 // update the row count as you delete a cell
// delete the row using the delete array with a fade animation
tableview.deleteRows(at: deleteArray, with: .fade)
}
override func viewDidLoad() {
super.viewDidLoad()
tableview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.8)
view.addSubview(tableview)
tableview.register(CustomTv.self, forCellReuseIdentifier: "cell")
tableview.delegate = self
tableview.dataSource = self
}
}
// you need to declare a cell delegate that will let your tableview know when the button was tapped on the cell
protocol CustomTvCellDelegate: AnyObject {
func deleteCell(_ customTV: CustomTv, location: CGPoint)
}
class CustomTv: UITableViewCell { // it's good form to Pascal case your class name ;)
weak var delegate: CustomTvCellDelegate? // make that delegate a property of your cell
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
return view
}()
lazy var btn : UIButton = {
let btn = UIButton(frame: CGRect(x: 50, y: 6, width: 100 , height: 110))
btn.backgroundColor = .blue
return btn
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
// moved these calls here instead of on setSelected(_selected:animated:)
addSubview(backView)
backView.addSubview(btn)
btn.addTarget(self, action:#selector(self.deleteCell), for: .touchUpInside)
}
@objc func deleteCell(sender: UIButton){
// let your cell delegate (tableview) know what the button got tapped, you need to pass the button here)
let buttonLocation = sender.superview?.convert(sender.frame.origin, to: nil) ?? CGPoint.zero
delegate?.deleteCell(self, location: buttonLocation)
}
}
How to delete a cell in tableView by clicking a button in a cell? Using coreData
OK Currently you are setting the selector of your done button to outside of its container (cell) this is bad practice in general, you are configuring the cell with a ToDo but not assigning the optional inside the cell, supposedly there to keep a reference to the ToDo.
In my opinion I would change this slightly so that you store the reference to the ToDo firstly:
func configureCell(toDo: ToDo) {
self.toDo = toDo
taskTitle.text = toDo.title
}
Now on your cell create a Protocol, then configure the cell with a ToDo and a delegate, then on button press tell the delegate your button was pressed with the relevant ToDo...
protocol ToDoCellDelegate: class {
func toDoCellButtonPressed(todo: ToDo?)
}
Now on your cell configure as:
func configureCell(toDo: ToDo, delegate: ToDoCellDelegate) {
self.delegate = delegate
self.toDo = toDo
taskTitle.text = toDo.title
}
and add a ref to the delegate in the cell:
weak var delegate: ToDoCellDelegate?
now change your buttons selector to a func inside the cell
func buttonPressed() {
self.delegate?.cellToDoButtonPressed(toDo: toDo)
}
Then in your VC you conform to the delegate passing self in the configuration and implement the delegate:
extension ItemDetailsVC: ToDoCellDelegate {
func toDoCellButtonPress(toDo: ToDo?) {
if let t = toDo {
//tell context to delete todo and remove cell.
}
}
}
Swift - remove cell from TableView after Button-Tap
You can access the tableView
and the indexPath
within the cell with this extension:
extension UITableViewCell {
var tableView: UITableView? {
return (next as? UITableView) ?? (parentViewController as? UITableViewController)?.tableView
}
var indexPath: IndexPath? {
return tableView?.indexPath(for: self)
}
}
With the help of this other extension:
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
So then you can delete the cell as usual:
tableView!.deleteRows(at: [indexPath!], with: .automatic)
Note that the tableView should be responsible for managing cells.
Related Topics
Type Alias Declaration with Templates in Swift
How to Pass Data Backwards to a View Controller After Passing Forward
Protocol Variable Implementing Another Protocol
Updating Existing Constraints Does Not Work, Wrong Use of .Active Property
Will a a Weak Wrapper Class Throw Off a Hashable Based Collection When The Wrapped Value Is Set Nil
Xcode Swift: Could Not Insert New Outlet Connection
Unexpectedly Found Nil While Unwrapping an Optional Value with Avaudioplayer
Choppy Animation Swiftui Nested Views
Downloading PDF Using Nsurlsession (Http Post) with Parameters
iOS 10. Coredata Insert New Object Sig Abrt
Swift: How to Get Image Name from Assets
How to Draw Something on a PDF in Swift
What's a Placeholder? Why Do We Need to Define Placeholder Data Type for Generics