mack mack - 29 days ago 15
Swift Question

Perform action button in uitableview cell to perform delete functionality

I have one table view, and in each cell i have

X
Button for delete the particular cell . So i have done the iboutlet of the button to my custom table view cell. And in my cell row at index path i have done the add target to my button. But when i press my button in my table view cell. App crash. If i put the braekpoint. Its showing in the target added code line.

Here my code :

func followButton(sender: AnyObject) {


if let button = sender as? UIButton {
print("Button Clicked: \(button.tag)")
let item = Addtocartdata[button.tag]
print("name: \(item.cartid!)")

let headers = [
"cache-control": "no-cache",
"postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec"
]

let jsonObj:Dictionary<String, Any> = [
"cartID" : "\(item.cartid!)",
"cartType" : "3"
]


if (!JSONSerialization.isValidJSONObject(jsonObj)) {
print("is not a valid json object")
return
}

if let postData = try? JSONSerialization.data(withJSONObject: jsonObj, options: JSONSerialization.WritingOptions.prettyPrinted) {
let request = NSMutableURLRequest(url: NSURL(string: "http://exp.Cart.php")! as URL,
cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
///print(error)
} else {

DispatchQueue.main.async(execute: {

if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject>
{
let status = json["status"] as? Int;

if(status == 1)
{

// self.tableView.reloadData()
print("items deleted")
self.tableView.reloadData()


}

}
})
}
})

dataTask.resume()
}


}

}

Answer

In Swift 3, action's argument is a selector, the syntax is #selector(method-signature). So the final code is:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cartcel", for: indexPath) as! cartTableViewCell
    cell.deleteButton.tag = indexPath.row;
    cell.deleteButton.addTarget(self, action: #selector(followButton(sender:)), for: .touchUpInside)

    return cell;
}

For your additional question:

I need to get the value of each cell and i need to pass as a parameter to one api call. So if it does not mach. Then how can i do the selector. To perform the delete functionality

func followButton(sender: AnyObject) {
    if let button = sender as? UIButton {
        print("Button Clicked: \(button.tag)")
        let item = Addtocartdata[button.tag]
        print("name: \(item.cartproName), quality: \(item.proqty), price: \(item.cartproPrice)")
    }
}