在我的tableview中,我只希望某些单元格能够根据条件向左拖动某些选项.其他单元格的行为应该像是禁用了commitEditingStyle.这可能吗?
使用下面的代码,我可以在满足条件时添加操作,但其他单元格仍然可以获得默认的“删除”操作.如何摆脱删除操作?
override func tableView(tableView: UITableView,commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView,editactionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let object = items[indexPath.row] if object.name == "name" { // someAction var addAction = UITableViewRowAction(style: .Default,title: "+") { (action: UITableViewRowAction!,indexPath: NSIndexPath!) -> Void in } return [addAction] } return nil }
使用下面的代码,我设法启用和禁用操作.但只能使用“删除”按钮.
override func tableView(tableView: UITableView,editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { let object = items[indexPath.row] if object.name == "joyce" { return UITableViewCellEditingStyle.Delete } else { return UITableViewCellEditingStyle.None } }
解决方法
您需要一种基于数据模型确定可编辑状态的方法.例如:
class Message { var subject : String var title : String var isEditable : Bool init(subject: String,title: String) { self.subject = subject self.title = title self.isEditable = true } }
有了这个,您可以轻松处理tableView:canEditRowAtIndexPath:delegate方法.您的视图控制器应如下所示:
class ViewController : UIViewController,UITableViewDataSource,UITableViewDelegate { var tableView : UITableView! var messages : [Message] // MARK: - UITableView Delegate func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return self.messages.count } func tableView(tableView: UITableView,canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { let message = self.messages[indexPath.row] return message.isEditable } }
在一些更复杂的例子中,它可能是计算属性,但整体概念是相同的.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。