Swift:在TableView中滑动动作以删除线

时间:2019-05-18 11:30:06

标签: ios swift uitableview tableview strikethrough

女士们先生们, 我目前已经习惯了Swift,并且想从一个小的待办事项应用程序开始。到目前为止,我可以添加一个项目并在上下文中永久地保护它。添加项目后,它将显示在表格视图中。现在,我想使用支票刷卡删除线项目,这些项目已添加,并且在我的上下文中可以安全地使用此信息。使用滑动删除功能效果很好。

有人知道如何实现吗?我试图自己解决它,但无法完成。之前曾在这里问过类似的问题,但没有得到正确的答案:Add strikethrough to tableview row with a swipe

func checkAccessoryType(cell: UITableViewCell, isCompleted: Bool) {
    if isCompleted {
        cell.accessoryType = .checkmark

    } else {
        cell.accessoryType = .none
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let todo = CoreDataManager.shared.getTodoItem(index: indexPath.row)
    todo.completed = !todo.completed
    CoreDataManager.shared.safeContext()

    if let cell = tableView.cellForRow(at: indexPath){
        checkAccessoryType(cell: cell, isCompleted: todo.completed)
    }
}

2 个答案:

答案 0 :(得分:2)

假设您试图删除任务的标题(应定义为标签),这是采取的方法:

1-确保将标签设置为属性文本,而不是纯文本。为此,请转到Main.storyboard,选择标签,然后在属性检查器中,将文本设置为Attributed。

2-在您的完成块(即滑动后执行的完成块)内部,添加以下代码:

SWIFT 5

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: taskLabel.text)
attributeString.addAttribute(.strikethroughStyle, value: 1, range: NSRange(location: 0, length: taskLabel.text.count))
taskLabel.attributedText = attributeString

仅需一点建议:如果在提问时添加一些代码,这总是有帮助的。 让我知道是否没有任何意义。

答案 1 :(得分:0)

查看您提供的链接,您需要在UITableViewCell上进行滑动操作

尝试调查:

  • leadingSwipeActionsConfigurationForRowAt
  • trailingSwipeActionsConfigurationForRowAt

您需要执行以下操作才能删除线标签或删除:

func tableView(_ tableView: UITableView,
                leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let closeAction = UIContextualAction(style: .normal, title:  "Close", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
             print("OK, marked as Closed")
             success(true)
         })
         closeAction.image = UIImage(named: "tick")
         closeAction.backgroundColor = .purple

         return UISwipeActionsConfiguration(actions: [closeAction])

 }

 func tableView(_ tableView: UITableView,
                trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let modifyAction = UIContextualAction(style: .normal, title:  "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
         print("Update action ...")
         success(true)
     })
     modifyAction.image = UIImage(named: "hammer")
     modifyAction.backgroundColor = .blue

     return UISwipeActionsConfiguration(actions: [modifyAction])
 }

Left Swipe

Right Swipe

来源:https://developerslogblog.wordpress.com/2017/06/28/ios-11-swipe-leftright-in-uitableviewcell/