我使用SWTableViewCell 在我自己的应用程序中实现这些操作。看看它很棒!
你可以像这样使用这个类:
1.导入 SWTableViewCell 类
点击上面的链接或在 github 上搜索 SWTableViewCell。下载 zip(或使用可可豆荚,如果您熟悉它们)。
打开解压后的目录,找到 PodsFile 目录。将此目录的内容拖到您的项目中。这样做应该会导致 Xcode 要求创建桥接头。同意它然后添加
#import "SWTableViewCell.h"
到那个桥接头文件。如果你编译你会得到一些解析问题错误:预期类型。要解决这些问题,只需添加
#import <UIKit/UIKit.h>
到 NSMutableArray+SWUtilityButtons.h。现在我们准备好摇滚了。
2。创建一个 SWTableViewCell 子类
好的,您可以按原样使用该单元格,但很可能您希望在简单的默认单元格外观之外增加该单元格。如果是这样,请创建一个新的可可触摸类(快速)并使您的单元格成为SWTableViewCell 的子类。它应该是这样的:
import UIKit
class MySWCell: SWTableViewCell {
}
如果您使用故事板,您可以在此类的 tableview 中制作单元格,连接任何出口/动作等。您需要做的所有可爱的事情来使单元格就像您需要的那样。
3.在 TableView 中使用您的子类
对于这个示例,我刚开始使用 Master-Detail 基础项目。您更改 cellForRowAtIndexPath 方法以使用新的自定义单元格:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as MySWCell
let object = objects[indexPath.row] as NSDate
cell.textLabel!.text = object.description
return cell
}
虽然这很棒,但您可能想要添加右/左实用按钮,这就是我们这样做的原因:
4.添加实用程序按钮
您可以在 cellForRowAtIndexPath 中执行此操作,但更愿意将其放在单独的函数中:
func getRightUtilityButtonsToCell()-> NSMutableArray{
var utilityButtons: NSMutableArray = NSMutableArray()
utilityButtons.sw_addUtilityButtonWithColor(UIColor.redColor(), title: NSLocalizedString("Delete", comment: ""))
utilityButtons.sw_addUtilityButtonWithColor(UIColor.blueColor(), title: NSLocalizedString("Email", comment: ""))
return utilityButtons
}
现在在您的cellForRowAtIndexPath 中使用此方法:
cell.rightUtilityButtons = self.getRightUtilityButtons();
如果您要在单元格上向左滑动,您将有两个按钮:
但是,这些按钮的作用并不大。我们需要遵守委托。
5.响应按钮
首先,告诉细胞你是它的代表。同样,在cellForRowAtIndexPath 中添加这一行:
cell.delegate = self;
然后将类定义调整为这样:
class MasterViewController: UITableViewController, SWTableViewCellDelegate
MasterViewController 将替换为您处理 tableview 数据源/委托的类的名称。
现在实现didTriggerRightUtilityButtonWithIndex函数:
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) {
if index == 0 {
println("delete button")
}else {
println("print button")
}
}
现在你准备好了!您还可以使用didTriggerRightUtilityButtonWithIndex 方法中的hideUtilityButtonsAnimated 方法告诉单元格做一些很酷的事情,例如在选择一个按钮后隐藏按钮:
cell.hideUtilityButtonsAnimated(true);
这个函数会在tableview滚动时隐藏单元格:
func swipeableTableViewCellShouldHideUtilityButtonsOnSwipe(cell: SWTableViewCell!) -> Bool {
return true
}
玩得开心,这是一组很棒的课程!