可操作
通过 可操作 可以使您更容易采用iOS中的委托模式的约定,减少冗余代码。
关于
当您想在iOS中将动作传递给对象的拥有者时,通常使用委托模式。在内置类中,这种模式看起来像
protocol UITextFieldDelegate: class {
func textFieldDidBeginEditing(UITextField)
...
func textFieldDidEndEditing(UITextField, reason: UITextField.DidEndEditingReason)
}
建议在函数中返回委托的对象 - 在这种情况下,是 UITextField
。这种命名惯例可能会变得冗长,但它有一些优点。您可能需要委托多个 UITextField
,并使用switch语句来消除歧义。这也使开发者更清楚地知道特定的函数 属于 UITextFieldDelegate
,而某些 func didBeginEditing()
则更加不清楚。
但是在开发过程中维持这种风格可能会很繁琐,并且需要大量的样板代码,特别是在较大的委托中。 可操作 利用 Sourcery 代码生成,使这些委托协议更容易编写和表达。
使用方法
首先,添加执行代码生成的构建阶段。在其之前插入编译源
阶段。指定您的输入文件(-i
)和输出将生成的文件位置(-o
)。确保输出文件已添加到您的Xcode项目中。
$PODS_ROOT/Actionable/actionable.sh -i $PROJECT_DIR/ -o $PROJECT_DIR/Generated/Actionable+Generated.swift
现在您准备好添加您的委托了。要符合可操作,只需声明一个委托和一系列动作
class TableViewCell: UITableViewCell, Actionable {
// Conforming to Actionable
weak var delegate: Delegate?
enum Action {
case didTapButton
}
func doSomething() {
// notify the delegate that something happened
notify(.didTapButton)
}
}
然后在另一边,符合新生成的委托
class TableViewController: UITableViewController, TableViewCellDelegate {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: TableViewCell.reuseID, for: indexPath)
as! TableViewCell
// assign the controller as the cell’s delegate
cell.delegate = self
return cell
}
// TableViewCellDelegate, and this function, were generated for you
func tableViewCell(_ cell: TableViewCell, didNotify action: TableViewCell.Action) {
switch action {
case .didTapButton:
print("Message received!")
}
}
}
示例
要运行示例项目,首先克隆仓库,然后在 Example 目录中运行 pod install
。您将看到一个示例表格视图,其按钮通过可操作的模式发送事件到 AppDelegate
。
要求
安装
可操作的组件通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'Actionable'
作者
Connor Neville, [email protected]
许可协议
可操作的组件在 MIT 许可协议下提供。有关更多信息,请参阅 LICENSE 文件。