这是一个快速而肮脏的例子。
假设你有一个类 Restaurant 有一个 name 和 likes 值:
class Restaurant {
var name: String?
var likes: Int = 0
}
您初始化了一堆Restaurant 对象,并将它们放入一个名为dataSource 的数组中。您的表格视图数据源方法将如下所示:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cell");
cell.textLabel?.text = dataSource[indexPath.row].name
return cell
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// This can be empty if you're not deleting any rows from the table with your edit actions
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
// First, create a share action with the number of likes
let shareAction = UITableViewRowAction(style: .Default, title: "\(self.dataSource[indexPath.row].likes)") { (action, indexPath) -> Void in
// In your closure, increment the number of likes for the restaurant, and slide the cell back over
self.dataSource[indexPath.row].likes++
self.tableView.setEditing(false, animated: true)
}
return [shareAction] // return your array of edit actions for your cell. In this case, we're only returning one action per row.
}
我不会从头开始编写可滚动单元格,因为this question 有很多可供您使用的选项。
然而,我对 Andrew Carter 尝试遍历子视图以直接在编辑操作中访问 UIButton 很感兴趣。这是我的尝试:
首先,创建一个对UITableViewCell(或单元格数组)的引用,您希望对其进行修改,在此示例中,我将使用单个单元格:
var cellRef: UITableViewCell?
// ...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cell");
cell.textLabel?.text = dataSource[indexPath.row].name
cellRef = cell;
return cell
}
在您的分享操作中,遍历按钮的子视图。我们正在寻找 UITableViewCellDeleteConfirmationView 和 _UITableViewCellActionButton 对象(链接以供参考的私有标头)。
let shareAction = UITableViewRowAction(style: .Default, title: "\(self.dataSource[indexPath.row].likes)") { (action, indexPath) -> Void in
var deleteConfirmationView: UIView? // UITableViewCellDeleteConfirmationView
if let subviews = self.cellRef?.subviews {
for subview in subviews {
if NSClassFromString("UITableViewCellDeleteConfirmationView") != nil {
if subview.isKindOfClass(NSClassFromString("UITableViewCellDeleteConfirmationView")!) {
deleteConfirmationView = subview
break
}
}
}
}
if let unwrappedDeleteView = deleteConfirmationView {
if unwrappedDeleteView.respondsToSelector("_actionButtons") {
let actionbuttons = unwrappedDeleteView.valueForKey("_actionButtons") as? [AnyObject]
if let actionButton = actionbuttons?.first as? UIButton { // _UITableViewCellActionButton
actionButton.setTitle("newText", forState: .Normal)
}
}
}
}