我有一个表格视图,在每个单元格中我都有X
按钮用于删除特定单元格。所以我已经完成了我的自定义表格视图单元格的按钮的iboutlet。在索引路径的单元格行中,我已经完成了向我的按钮添加目标。但是当我在表格视图单元格中按下我的按钮时。应用崩溃。如果我把braekpoint。它在目标中显示添加了代码行。
这是我的代码:
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()
}
}
}
答案 0 :(得分:3)
要从swift2.2或更高版本添加选择器,语法会更改,您必须像这样添加目标
perf_events
这是你将获得该单元格的索引路径的方法,使用索引路径可以完成剩下的工作
cell.deleteButton.addTarget(self, action:#selector(followButton(sender:)), for: .touchUpInside)
答案 1 :(得分:2)
在Swift 3中,action
的参数是一个选择器,语法为#selector(method-signature)
。所以最终的代码是:
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;
}
有关您的其他问题:
我需要获取每个单元格的值,我需要作为参数传递 一个api电话。所以,如果它不是马赫。那怎么办呢 选择。执行删除功能
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)")
}
}