一个具有精美 UI 组件的库,可更快地构建 SwiftUI 和 UIKit 应用程序。
将 ComponentsKit 作为包依赖项添加到 Xcode 项目
https://github.com/componentskit/ComponentsKit
。库中的所有组件都有 view models
,应该使用它们来配置它们的外观。这些模型在 SwiftUI 和 UIKit 组件之间共享。例如,可以按如下方式配置输入字段
let inputFieldVM = InputFieldVM {
$0.title = "Email"
$0.placeholder = "Enter your email"
$0.isRequired = true
}
注意
ComponentsKit 中的所有 view models
都没有逐个成员的初始化器。相反,它们符合 ComponentVM
协议,该协议定义了一个修改默认值的初始化器
/// Initializes a new instance by applying a transformation closure to the default values.
///
/// - Parameter transform: A closure that defines the transformation.
init(_ transform: (_ value: inout Self) -> Void)
这种方法有两个主要好处
要控制 SwiftUI 中的行为,您应该使用 bindings
@State var email: String
@FocusState var isEmailFieldFocused: Bool
SUInputField(
text: $email,
isFocused: $isEmailFieldFocused,
model: inputFieldVM
)
// Track changes in the inputted text
.onChange(of: self.email) { oldValue, newValue in
...
}
// Control the focus (e.g., hide the keyboard)
isEmailFieldFocused = false
要控制 UIKit 中的行为,您应该使用组件的公共变量
let inputField = UKInputField(model: inputFieldVM)
// Access the text
var inputtedText = inputField.text
// Assign a new closure to handle text changes
inputField.onValueChange = { newText in
inputtedText = newText
}
// Control the focus (e.g., hide the keyboard)
inputField.resignFirstResponder()
配置
该库带有预定义的字体、大小和颜色,但您可以更改这些值以自定义应用程序的外观。为此,请修改配置
ComponentsKitConfig.shared.update {
// Update colors
$0.colors.primary = ...
// Update layout
$0.layout.componentRadius.medium = ...
}
注意
设置初始配置的最佳位置是在 func application(_:, didFinishLaunchingWithOptions:) -> Bool
方法中,该方法位于您的 AppDelegate
中,或者位于 SceneDelegate
中的类似方法中。
通过修改配置,您还可以为您的应用程序创建自定义主题。为此,首先创建一个配置的新实例
let halloweenTheme = ComponentsKitConfig {
$0.colors.background = .themed(
light: .hex("#e38f36"),
dark: .hex("#ba5421")
)
...
}
当用户切换主题时,通过将其分配给 shared
实例来应用它
ComponentsKitConfig.shared = halloweenTheme
扩展颜色
来自配置的所有颜色都可以在应用程序中使用。例如
// in UIKit
view.backgroundColor = UniversalColor.background.uiColor
// in SwiftUI
UniversalColor.background.color
如果您想使用未包含在配置中的其他颜色,您可以扩展 UniversalColor
extension UniversalColor {
static var special: UniversalColor {
if selectedTheme == .halloween {
return ...
} else {
return ...
}
}
}
// Then in your class
let view = UIView()
view.backgroundColor = UniversalColor.special.uiColor
扩展字体
如果您想使用未包含在配置中的其他字体,您可以扩展 UniversalFont
extension UniversalFont {
static let title: UniversalFont = .system(size: 16, weight: .regular)
}
// Then in your view
Text("Hello, World")
.font(UniversalFont.title.font)
您还可以扩展 UniversalFont
以更轻松地访问自定义字体
extension UniversalFont {
static func myFont(ofSize size: CGFloat, weight: Weight) -> UniversalFont {
switch weight {
case .regular:
return ...
}
}
}
// Then in your view
Text("Hello, World")
.font(UniversalFont.myFont(ofSize: 14, weight: .regular).font)