tôi vật lộn với điều này cũng nhưng cuối cùng phát hiện ra một giải pháp - Tôi đang chạy XCode 8.3.2. Rất nhiều câu trả lời tôi đọc là dành cho các phiên bản cũ của XCode/Swift và nhiều phiên bản dành cho Objective-C.
Giải pháp tôi tìm thấy là sử dụng công cụ 'editActionsForRowAt' cho UITableViews. Lưu ý: Mọi thứ khác tôi đọc tiếp tục chỉ cho tôi về công cụ 'commit editingStyle' cho UITableView, nhưng tôi không bao giờ có thể làm việc đó. Sử dụng editActionsForRowAt hoạt động hoàn hảo cho tôi.
LƯU Ý: 'postData' là tên của Mảng mà tôi đã thêm dữ liệu vào.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, IndexPath) in
// Remove item from the array
postData.remove(at: IndexPath.row)
// Delete the row from the table view
tableView.deleteRows(at: [IndexPath as IndexPath], with: .fade)
})
// set DeleteAction Button to RED (this line is optional - it simply allows you to change the color of the Delete button - remove it if you wish)
deleteAction.backgroundColor = UIColor.red
return [deleteAction]
}
Tôi cũng có một số mã để thêm một 'nút EDIT' bên cạnh nút Delete:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, IndexPath) in
//print("Edit tapped")
})
// Set EditAction button to blue (this line is not mandatory - it just sets the color of the Edit box to blue)
editAction.backgroundColor = UIColor.blue
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, IndexPath) in
//print("Delete tapped")
// Remove item from the array
postData.remove(at: IndexPath.row)
// Delete the row from the table view
tableView.deleteRows(at: [IndexPath as IndexPath], with: .fade)
})
// set DeleteAction Button to RED (this line isn't mandatory - it just sets the color of the Delete box)
deleteAction.backgroundColor = UIColor.green
return [editAction, deleteAction]
}
EDIT: cố định định dạng do đó, mã xuất hiện trong hộp màu xám :)
Nguồn
2017-04-26 17:26:34
tôi nghĩ rằng u kiểm tra cú pháp hàm –
func tableView (tableView: UITableView, commitEditingStyle ed itingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { –
@LeonardoSavioDabus Tôi đã sử dụng cú pháp tương tự như bạn đã đề xuất và tôi cũng đã cập nhật câu hỏi của mình nhưng vẫn chưa xóa nút. –