class YourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {
@IBOutlet weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "identifier") as? CustomCell else {
return UITableViewCell()
}
cell.indexPath = indexPath
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return nil
}
func delete(for cell: CustomCell) {
let indexPath = cell.indexPath
print("doing action for cell at: \(indexPath!.row)")
// your implementation for action
// maybe delete a cell or whatever?
cell.hideDeleteActions()
}
}
protocol CustomCellDelegate: class {
func delete(for cell: CustomCell)
}
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate?
var indexPath: IndexPath!
@IBOutlet weak var buttonAction: UIButton?
@IBOutlet weak var constBtnDeleteAction: NSLayoutConstraint?
override func awakeFromNib() {
self.constBtnDeleteAction?.constant = 0
}
override func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else {
return
}
if self.point(inside: point, with: event) {
self.showDeleteActions()
}
}
func showDeleteActions() {
self.constBtnDeleteAction?.constant = 100
// Set it according to the button width
UIView.animate(withDuration: 0.3) {
self.layoutIfNeeded()
}
}
func hideDeleteActions() {
self.constBtnDeleteAction?.constant = 0
UIView.animate(withDuration: 0.3) {
self.layoutIfNeeded()
}
}
@IBAction func cellButtonAction() {
delegate?.delete(for: self)
}
}
你需要做更多像故事板一样的设置按钮的约束,它将在单元格的最右边,并加入插座。