APGenericSearchTextField 0.2.2

APGenericSearchTextField 0.2.2

Bellaposa 维护。



APGenericSearchTextField

CI Status Version License Platform

上下文

Swift 4 引入了一种新的类型称为 KeyPath,它允许访问对象的属性。
例如

let helloWorld = "HelloWorld" let keyPathCount = \String.count

let count = helloWorld[keyPath: keyPathCount]
//count == 10

语法可以非常简洁,支持类型推断和属性链。

用途

很久以前,我需要创建一个搜索文本框,并认为将它应用到这个概念上会很好。

内部原理

  • KeyPath
  • NSPredicate

示例

运行示例项目,首先克隆仓库,然后从示例目录运行pod install

详细信息

需要遵循几个简单的步骤

  1. 通过从NSObject派生定义你的模型
  2. 使用@objc定义属性
  3. 选择过滤器操作符
  4. 选择要过滤的属性
  5. 定义你的单元格配置器

模型

class Person: NSObject {
	@objc let name: String
	@objc let surname: String

	init(name: String, surname: String) {
		self.name = name
		self.surname = surname
	}
}

过滤器操作符

目前只支持两种操作符

  1. 包含
  2. 等于

要过滤的属性

使用keyPath,你可以选择你想要比较的域。

例如:如果你想要通过名称过滤数组对象,可以使用\.name

单元格配置器

你可以这样配置你的单元格

searchTextField.cellConfigurator = { [weak self] (person, cell) in
			cell.textLabel?.text = person.name
}

自定义

可以通过以下这些值自定义您的建议TableView

tableXOffset
tableYOffset
tableCornerRadius
tableBottomMargin
maxResultsListHeight
minCharactersNumberToStartFiltering

singleItemHandler 将返回tableView中选中的对象

singleItemHandler = { [weak self] value in
		print(value)
}

Storyboard

Storyboards存在一个与通用类相关的问题。问题是Interface Builder通过Objective-C运行时与ViewController通信。因此,Interface Builder受限于Objective-C提供的特性。在这个例子中,泛型不被支持。顺便说一下,有一个方法可以在Storyboard中使用泛型类。

您需要:

  • 声明一个扩展了GenericSearchTextField的自定义UITextField并将其添加到Storyboard中即 class SearchTextField: GenericSearchTextField{}

  • 定义输出接口

    • 定义类型为SearchTextField的输出接口时,XCode会报告错误。重要的是将类型从SearchTextField更改为UIView
    • 之前: @IBOutlet weak var textField: SearchTextField!
    • 之后: @IBOutlet weak var textField: UIView!
  • 定义类型为GenericSearchTextField的计算属性

    • 将变量转换为GenericSearchTextField
    • 现在您可以使用变量了
var searchTextField: GenericSearchTextField<Person> {
		return textField as! GenericSearchTextField
}
  • 使用searchTextField变量

Bugs

此库处于alpha阶段
发现了bug?简单的Pull Request

TODOs

  • 更好的测试覆盖率
  • 更好的过滤管理
  • 自定义单元格支持
  • Storyboard支持

Demo

查看示例项目。您将找到两个示例,一个是通过代码实现,另一个是通过Storyboard实现的。

要求

安装

APGenericSearchTextField 通过 CocoaPods 提供。要安装它,只需在 Podfile 中添加以下行

pod 'APGenericSearchTextField'

作者

Bellaposa, [email protected]

许可证

APGenericSearchTextField 采用 MIT 许可证。有关更多信息,请参阅 LICENSE 文件。