hg56
hg56

Reputation: 185

Swipe to delete with multiple options

When the user swipes a table view cell in the chat view controller I would like to offer the option to either Block and delete that user, or to only delete the chat from the user. Is there a way I can have the swipe to delete option to have both options available? Should I be adding the block user option on a different page or will there be a way to have both in the commit editingStyle function.

class Conversation {
var key:String
var sender:String
var recipient:String
var date:Date
var recentMessage:String
var seen:Bool

init(key:String, sender: String, recipient:String, date:Date, recentMessage:String, seen:Bool) {
    self.key = key
    self.sender = sender
    self.recipient = recipient
    self.date = date
    self.recentMessage = recentMessage
    self.seen = seen
}

// Returns the UID of the conversations partner
// i.e NOT the UID of the current user
var partner_uid:String {
    guard let uid = Auth.auth().currentUser?.uid else { return "" }
    if sender != uid {
        return sender
    }
    return recipient
}

func printAll() {
    print("key: \(key)")
    print("sender: \(sender)")

    print("recentMessage: \(recentMessage)")
}
 }

   class ChatsTableViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableView:UITableView!

var conversations = [Conversation]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView = UITableView(frame: view.bounds)
    let nib = UINib(nibName: "ChatTableViewCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "chatCell")
    tableView.delegate = self
    tableView.dataSource = self
    tableView.reloadData()

    title = "CHAT"
    view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let cell = tableView.cellForRow(at: indexPath) as! ChatTableViewCell
        let name = cell.usernameLabel.text!

        let actionSheet = UIAlertController(title: "Block conversation with \(name)?", message: "Further messages from \(name) will be muted.", preferredStyle: .alert)

        let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }



        actionSheet.addAction(cancelActionButton)

        let deleteActionButton: UIAlertAction = UIAlertAction(title: "Block", style: .destructive)
        { action -> Void in
            self.muteConversation(self.conversations[indexPath.row])
        }

        let deleteOnlyButton: UIAlertAction = UIAlertAction(title: "Only Delete", style: .destructive)
        { action -> Void in


            print("only delete selected ")
        }

        actionSheet.addAction(deleteActionButton)
        actionSheet.addAction(deleteOnlyButton)
        self.present(actionSheet, animated: true, completion: nil)
    }
}

func muteConversation(_ conversation:Conversation) {
    guard let user = Auth.auth().currentUser else { return }
    let ref = Database.database().reference()

    let obj = [
        "social/blocked/\(user.uid)/\(conversation.partner_uid)" : true,
        "social/blockedBy/\(conversation.partner_uid)/\(user.uid)" : true,
        "conversations/users/\(user.uid)/\(conversation.partner_uid)/muted": true
    ] as [String:Any]
    print("OBBJ: \(obj)")
    ref.updateChildValues(obj, withCompletionBlock: { error, ref in
        if error != nil {
            let alert = UIAlertController(title: "Error deleting conversation!", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        } else {
            let alert = UIAlertController(title: "Conversation blocked!", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        }
    })
}

}

Upvotes: 2

Views: 1316

Answers (3)

SwiftNinja95
SwiftNinja95

Reputation: 157

Try this code and replace Action1 & Action2 with your preferred actions.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let action1 = UITableViewRowAction(style: .default, title: "Action1", handler: {
    (action, indexPath) in
    print("Action1")
})
action1.backgroundColor = UIColor.lightGray
let action2 = UITableViewRowAction(style: .default, title: "Action2", handler: {
    (action, indexPath) in
    print("Action2")
})
return [action1, action2]
}

Upvotes: 4

Waris Shams
Waris Shams

Reputation: 1614

You can modify your function like this to work

 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let blockAction = UITableViewRowAction(style: .normal, title: "Block") { (rowAction, indexPath) in

        self.muteConversation(self.conversations[indexPath.row])

    }
    let deleteAction  = UITableViewRowAction(style: .destructive, title: "Only Delete") { (rowAction, indexPath) in
        print("only delete selected ")
    }

    blockAction.backgroundColor = UIColor.gray
    return [blockAction, deleteAction]
}

and if you want to show action sheet instead you can use this code

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let moreAction = UITableViewRowAction(style: .normal, title: "More") { (rowAction, indexPath) in

        self.showActionSheet(indexPath)
    }

    moreAction.backgroundColor = UIColor.blue

    return [moreAction]
}

func showActionSheet(_ indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! ChatTableViewCell
    let name = cell.usernameLabel.text!

    let actionSheet = UIAlertController(title: "Block conversation with \(name)?", message: "Further messages from \(name) will be muted.", preferredStyle: .alert)

    let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }



    actionSheet.addAction(cancelActionButton)

    let deleteActionButton: UIAlertAction = UIAlertAction(title: "Block", style: .destructive)
    { action -> Void in
        self.muteConversation(self.conversations[indexPath.row])
    }

    let deleteOnlyButton: UIAlertAction = UIAlertAction(title: "Only Delete", style: .destructive)
    { action -> Void in


        print("only delete selected ")
    }

    actionSheet.addAction(deleteActionButton)
    actionSheet.addAction(deleteOnlyButton)

    self.present(actionSheet, animated: true, completion: nil)
}

Upvotes: 0

Abirami Bala
Abirami Bala

Reputation: 790

Download/Refer https://github.com/CEWendel/SWTableViewCell/archive/master.zip, integrate this third party library to your project and try the below code in your ViewController Step 1: add the delegate SWTableViewCellDelegate to your ViewController Step 2: in your cellForRow

 cell.leftUtilityButtons = leftButtons() as [AnyObject]
 cell.rightUtilityButtons = self.rightButtons() as [AnyObject]
 cell.delegate = self;

Step 3: customise your left/right side buttons on swipes

func leftButtons() -> NSMutableArray
{

    let leftUtilityButtons : NSMutableArray = NSMutableArray()
    leftUtilityButtons.sw_addUtilityButton(with: UIColor.orange, title: "Block")
    leftUtilityButtons.sw_addUtilityButton(with: UIColor.green, title: "Remove User")

    return leftUtilityButtons
}

func rightButtons() -> NSMutableArray {

    let leftUtilityButtons : NSMutableArray = NSMutableArray()
    leftUtilityButtons.sw_addUtilityButton(with: UIColor.red, title: "Delete Chat")

    return leftUtilityButtons
}

Step 4: handle actions with these two delegate methods

// click event on left utility button   
func swipeableTableViewCell(_ cell: SWTableViewCell, didTriggerLeftUtilityButtonWith index: Int)
{

    switch index
    {
    case 0:
     // Handle your button1 action (Block User)
     break

    case 1: break
     // Handle your button2 action (Remove User)

    default:
        break
    }
}
// click event on right utility button

func swipeableTableViewCell(_ cell: SWTableViewCell, didTriggerRightUtilityButtonWith index: Int)
{
    //handle your right button action (Delete Chat)
}

Thats it...!

Upvotes: 2

Related Questions