0

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) 
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
saner
  • 821
  • 2
  • 10
  • 32

5 Answers5

1

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)
Himanshu gupta
  • 650
  • 5
  • 10
  • adding self did not worked in the tableviewcell. Anoy other way? – saner Jun 09 '15 at 10:01
  • not self see the syntax, it is different from what you have in your code. – Himanshu gupta Jun 09 '15 at 10:09
  • I tried this: self.presentViewController(refreshAlert, animated: true, completion: nil) – saner Jun 09 '15 at 10:16
  • Oh, you are using this code from inside a separate cell file -> Custom cell. That is not the way to go... Instead: this will help: http://stackoverflow.com/questions/22904164/presentviewcontroller-from-custom-tablecell-in-xib – Himanshu gupta Jun 09 '15 at 10:30
1

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()
    }
}
Shankar BS
  • 8,394
  • 6
  • 41
  • 53
  • Hello Shan, how can I do it in swift? – saner Jun 09 '15 at 10:57
  • it is in swift just do or copy what i did in control and in custom cell – Shankar BS Jun 09 '15 at 11:03
  • I updated the cell part, but when I anter the "CellDelegate" to the class next to "UITableViewDelegate" it gives error as : does not conform to protocol "CellDelegate" – saner Jun 09 '15 at 11:38
  • also modify the controller class where u need to confirm to delegate as u do for setting table delegate and datasource – Shankar BS Jun 09 '15 at 11:40
  • i commented at each part where to modify please read it fully and also implement the delegate method in controller – Shankar BS Jun 09 '15 at 11:41
  • add the method `func deleteCell(cell:CustomCommentCell)` in controller or just copy and paste it from above code – Shankar BS Jun 09 '15 at 11:43
  • and also set `cell?.delegate = self` in `cellForRowAtIndexPath` method as i am doing in the code or else delegate won't call – Shankar BS Jun 09 '15 at 11:46
  • var indexPath: NSIndexPath = self.issueTableView.indexPathForCell(deleteCell!)! here getting error like does not have a member named "issue table view" – saner Jun 09 '15 at 12:03
  • replace `issueTableview` with your tableview outlet name, i just added it as an example replace with your tableview name – Shankar BS Jun 09 '15 at 12:06
  • also edited the code regarding the `issueTableview ` – Shankar BS Jun 09 '15 at 12:14
  • Code runs now, but when I click the delete button: terminating with uncaught exception of type NSException . . . By the way, thank you very very much Shan for the help, you are great. – saner Jun 09 '15 at 12:22
  • which one u are using if are using alert view implement the delegate method or alert controller there is no need, add the last method `func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)` in my code – Shankar BS Jun 09 '15 at 12:28
  • it should not crash check it once after adding the method `func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)` in my answer – Shankar BS Jun 09 '15 at 12:31
  • It worked great. That was the most detailed help I got from stackoverflow. Thank you very much Shan. – saner Jun 09 '15 at 13:44
1

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))

    }
}
sarac
  • 56
  • 3
0

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.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • How can I start a funcion specificly for that indexpath.row of the cell in wich the button is clicked? – saner Jun 09 '15 at 10:03
  • Currently where is the callback for the button located? In UITableViewController or UITableViewCell? – Shamas S Jun 09 '15 at 10:07
  • in the UITableViewCell – saner Jun 09 '15 at 10:10
  • I'm guessing that you'll be using reusable cells. If the callback is working all right right now for the button, you should save the indexPath of the cell in the UITableViewCell and update it each time in your 'cellforRowAtIndexPath' – Shamas S Jun 09 '15 at 10:26
0
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)
Jordan Davies
  • 9,925
  • 6
  • 40
  • 51