Confirmation for deleting a post in Table View Cell?

2.2k views Asked by At

I have a UItableview in which I have cells that shows post of the users.

I want users to have the ability to delete their post with a "delete button" that is showed in their post.

I can do it but I want users to have a confirmation pop-up first when they click the delete button in the cell.

So I am adding the code below as an action in the "cell" file of the table, but I get an error which say "use of unresolved identifier presentviewcontroller".

Can I not use the presentviewcontroller inside a cell file?

@IBAction func button_clicked(sender: AnyObject) {
    var refreshAlert = UIAlertController(title: "Refresh", message: "Do you want to delete this post?", preferredStyle: UIAlertControllerStyle.Alert)

    refreshAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in
        println("Handle Ok logic here")
    }))

    refreshAlert.addAction(UIAlertAction(title: "No", style: .Default, handler: { (action: UIAlertAction!) in
        println("Handle Cancel Logic here")
    }))

    presentViewController(refreshAlert, self, completion: nil) 
}
5

There are 5 answers

14
Shankar BS On BEST ANSWER

Hmm, better use alert control in the view controller, because in controller, u can get every thing like tableview (say after deleting comment u have to reload), the data to be delete (something which is present in the (for example)array that u are used to display in tableview)... etc

first define a delegate method in the cell file for example

 import UIKit
 @objc protocol CellDelegate
 {
     func deleteCell(cell:CustomCommentCell)
 }
 class CustomCommentCell: UITableViewCell {
 @IBOutlet weak var deleteButton: UIButton!  //a delete button
 weak var delegate:CellDelegate?   //declare a delegate 

  override init(style: UITableViewCellStyle, reuseIdentifier: String?)
 {
     super.init(style: style, reuseIdentifier: reuseIdentifier)     
 }

 required init(coder aDecoder: NSCoder)
 {
    super.init(coder: aDecoder)
 }

 override func awakeFromNib() {
     super.awakeFromNib()
     // Initialization code
 }

 //other code
 //......
 @IBAction func button_clicked(sender: AnyObject)
 {
    self.delegate?.deleteCell(self) //call the delegat method
 }

in the ViewController

import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, CellDelegate,UIAlertViewDelegate // add `CellDelegate`,UIAlertViewDelegate if u want  t use alert view
{
   //...other code
   // ....

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell:CustomCommentCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? CustomCommentCell;
       if(cell == nil)
       {
        //..cell initilise
       }
       cell?.delegate = self  //set the delegate to self
       //..other code set up comment string .. etc
       return cell!;
   }

   //define custom delegate method hear u can delete the cell
   //since u are passing the cell so u can get the index path of the cell 
   func deleteCell(cell: CustomCommentCell)
   {
    var deleteCell:CustomCommentCell? = cell as CustomCommentCell
    var indexPath: NSIndexPath  = self.tableView.indexPathForCell(deleteCell!)! //get the index path
    //using alert view
    var alertToDelete: UIAlertView = UIAlertView(title: "Delete", message: "Are u sure to delete this comment", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Ok")
    alertToDelete.show()

    /*  uncomment if u want to use alertControl and comment above 2 line of alertView
    //using alert control 
    var refreshAlert = UIAlertController(title: "Refresh", message: "Do you want to delete this post?", preferredStyle: UIAlertControllerStyle.Alert)
    refreshAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in
        println("Handle Ok logic here")
        //after deleting from datasource
        self.tableView.reloadData()
    }))

    refreshAlert.addAction(UIAlertAction(title: "No", style: .Default, handler: { (action: UIAlertAction!) in
        println("Handle Cancel Logic here")
    }))

    self.presentViewController(refreshAlert, animated: true, completion: nil)
    */

  }

//suppose if u use alert view u will get delegate call back in this check which button is clicked 
 func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
    if(buttonIndex == alertView.cancelButtonIndex)
    {
        //do nothing
        println("Handle Cancel Logic here")
    }
    else
    {
        //delete hear
        println("Handle Ok logic here")
        //after deleting form datasource
        self.tableView.reloadData()
    }
}
4
Shamas S On

I am not sure whether you can do it or not. But you should definitely not do it. Writing a 'controller' code inside a view class is most definitely not the way to do.

If I were you, I would do something like this.

Once the delete button in the row is pressed, a function in the UITableViewController should be called for the indexPath of the row.

This confirmationToDeleteIndexPath function of yours should present the refreshAlert and ask the user. On its callback you should attempt to delete the indexPath that was requested earlier.

4
Himanshu gupta On

The syntax is this:

self.presentViewController(<viewControllerToPresent: UIViewController>, animated: <Bool>, completion: <(() -> Void)?() -> Void>)

so, you need to do something like this:

self.presentViewController(refreshAlert, animated: true, completion: nil)
0
ashwini nagaraj On
let refreshAlert = UIAlertController(title: "Refresh", message: "Do you want to delete this post?", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
    //perform your action
}))

refreshAlert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action: UIAlertAction!) in
    //perform your action
}))

present(refreshAlert, animated: true, completion: nil)
0
sarac On

This is a solution I've used before - when the user swipes on the record in the table, they see the delete key. When selected, they get a pop-up that asks if they want to confirm the delete.

Lots of different ways to achieve this, probably better methods, but hope this helps someone.

In the view controller that contains the table, I included the following code:

// Code to handle delete records in tableview.
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        let uiAlert = UIAlertController(title: "Delete Record", message: "Are you sure you want to delete this record?", preferredStyle: UIAlertControllerStyle.Alert)
        self.presentViewController(uiAlert, animated: true, completion: nil)

        uiAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { action in
            //remove from data source
            self.managedObjectContext.deleteObject(self.fetchedResults[indexPath.row] as! NSManagedObject)
            do {
                try self.managedObjectContext.save()
            } catch _ {
            }

            // refresh table & header
            self.fetchData()
        }))

        uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

    }
}