概述
FormUI 提供了一种简便的方式来构建原生形式的 iOS。它受到 SwiftUI 的启发,并利用了 Combine 和结果构建器等新技术。然而,它完全是使用 UIKit 实现,这为其提供了更多的定制选项。
FormUI 致力于轻量级和无偏见。它解决了制作表单时的麻烦部分——如计数部分和隐藏行——但让您来填写特定用例的细节。
示例
![]() |
![]() |
![]() |
---|
需求
- iOS 13.0+
- Swift 5.3+
安装
这是 FormUI 的预发布版本。API 可能会受到警告而更改。
Swift 包管理器
要使用 Swift 包管理器安装 FormUI,请将以下值添加到您的 Package.swift
dependencies: [
.package(url: "https://github.com/james01/FormUI.git", .upToNextMajor(from: "0.1.0"))
]
使用方法
创建表单
通过子类化 FormViewController
来创建表单。
import FormUI
class MyFormViewController: FormViewController {
convenience init() {
self.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
form = Form {
Section {
Row(style: .default) { (cell) in
cell.textLabel?.text = "Hello World"
}
}
}
}
}
Form
和Section
构造函数利用了 Swift 5.1 中非官方引入、 Swift 5.4 中正式引入的 结果构建器 功能。
处理行选择
通过向行的 onSelect(_:)
方法传递一个处理程序来处理行选择。每次选择行时,都会调用此处理程序。
Row(style: .default) { (cell) in
cell.textLabel?.text = "Tap Me"
}.onSelect { (tableView, indexPath) in
tableView.deselectRow(at: indexPath, animated: true)
print("Hello World")
}
动态隐藏和显示行
FormUI 使隐藏和显示行变得容易。当使用默认的 UITableView
时,这是一个复杂的任务。
首先,定义一个已发布的变量来跟踪行是否被隐藏。
@Published var isRowHidden = true
然后,将该变量的投影值(即 $isRowHidden
)传递给您想要隐藏的行的 hidden(_:)
方法。每次 isRowHidden
改变其值时,行将自动显示或隐藏。
有关
Published
属性包装器的更多信息,请参阅其 文档。
Section {
Row(style: .default) { (cell) in
cell.textLabel?.text = "Tap to Toggle Row"
}.onSelect { (tableView, indexPath) in
tableView.deselectRow(at: indexPath, animated: true)
self.isRowHidden.toggle()
}
Row(style: .default) { (cell: UITableViewCell) in
cell.textLabel?.text = "Hidden"
}.hidden($isRowHidden)
Row(style: .default) { (cell) in
cell.textLabel?.text = "Not Hidden"
}
}
您可以使用类似的方式隐藏和显示部分。
ForEach
使用通常情况下,您可能需要从枚举等静态数据源生成行或部分。在这些情况下,可以使用ForEach
。
enum Theme: String, CaseIterable {
case light
case dark
case system
}
...
Section(header: "Theme") {
ForEach(Theme.self) { (theme) -> Row in
Row(style: .default) { (cell) in
cell.textLabel?.text = theme.rawValue.capitalized
}
}
}
ForEach
还可以与数据数组一起使用。
let desserts = [
"🍪 Cookies",
"🍫 Chocolate",
"🍦 Ice Cream",
"🍭 Candy",
"🍩 Doughnuts",
"🍰 Cake"
]
...
Section(header: "Desserts") {
ForEach(0..<desserts.count) { (n) -> Row in
Row(style: .default) { (cell) in
cell.textLabel?.text = desserts[n]
}
}
}
作者
詹姆斯·兰道夫 (@jamesrandolph01)
许可协议
FormUI采用MIT许可协议发布。有关详细信息,请参阅LICENSE。