是否可以手动调用UITableview的editActionsForRowAt



在我的项目中,需要对按钮操作调用UITableVieweditActionsForRowAt。因此,单击该按钮后,tableview向左滑动。

我的编辑ActionsForRowAt代码:

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

let editAction = UITableViewRowAction(style: .normal, title: "Edit".localized) {[weak self] (rowAction, indexPath) in
// Perform edit action here
}
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete".localized) {[weak self] (rowAction, indexPath) in
// Perform delete action here
}
return [deleteAction,editAction]
}

我不知道这是否可能?我搜索了很多,但没有找到任何解决方案。请提出可能与否?如果是,那么如何实现这一点?

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)
}
}

你需要做更多类似故事板的按钮设置约束,按钮将在单元格的最右边,并加入出口。

我认为通过调用下面的表视图的委托方法是可能的

@IBAction func editingstylecalled(_ sender:UIButton)
{
let tag = sender.tag
self.tableView(self.tableview, commit: .delete, forRowAt: IndexPath.init(row: tag, section: 0))
}

请在上面的代码中设置您的表视图并进行检查。

最新更新