DataEntryToolbar 是一个 UIToolbar 的子类,旨在用作键盘或选择器的输入辅助视图,提供“下一个”、“上一个”和“完成”按钮以在动态 tableView 中导航。
在您的 TableViewController
子类中创建一个 DataEntryToolbar
实例。确保在初始化器中提供您的 tableView
private lazy var dataEntryToolbar: DataEntryToolbar? = {
if let dataEntryToolbar = DataEntryToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44),
table:self.tableView) as DataEntryToolbar? {
// implement closures to be notified when buttons are tapped for additional customization:
...
dataEntryToolbar.didTapDoneButtonFromTextField = { (lastActiveTextField) in
if let textField = lastActiveTextField {
self.textFieldShouldReturn(textField)
}
}
...
return dataEntryToolbar
} else {
return nil
}
}()
cellForRowAtIndexPath
中,将 DataEntryToolbar
实例设置为 cell 的文本字段的 inputAccessoryView
。此外,使用当前 indexPath 作为键将该文本字段添加到 tableTextFields
字典中
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.section) {
// first section -- basic info
case TableSections.BasicInfo.rawValue:
switch (indexPath.row) {
case 0:
let nameCell = tableView.dequeueReusableCellWithIdentifier("NameCell",
forIndexPath: indexPath) as JDCustomTextFieldCell
nameCell.textField.inputAccessoryView = self.dataEntryToolbar
self.dataEntryToolbar?.tableTextFields[indexPath] = nameCell.textField
nameCell.textField.text = self.textFieldData[indexPath]
return nameCell
}
`...`
}
`...`
}
您可以通过几种方式自定义工具栏的外观。可以在初始化器中指定高度,或者更改工具栏本身的颜色或其按钮的颜色
// adjust bar's tint color
self.dataEntryToolbar.barTintColor = UIColor.darkGrayColor()
// adjust prev/next button tint colors
self.dataEntryToolbar.previousButton.tintColor = UIColor.blueColor()
如果使用 UITableViewController
的子类,活动文本字段总是会自动滚动到键盘上方,以便用户可以看到它。如果您在一个普通的 UIViewController
中使用 UITableView
,您将必须自己实现此功能。
欢迎提出建议或改进!
要运行示例项目,克隆仓库,然后首先从 Example 目录运行 pod install
。
jeff,[email protected]
DataEntryToolbar 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。