为Swift UI视图创建自定义修饰符 [英] Creating custom modifiers for Swift UI views
问题描述
想知道如何为Swift UI视图创建修饰符吗?
Was wondering how it's possible to create modifiers for Swift UI views?
例如,假设我有一些这样定义的视图:
For example, let's say I have some view defined as so:
struct LabelView: View {
let font1: Font = .header
let font2: Font = .body
var body: Some View {
// two views, where one uses font1 and other uses font2
}
}
如何创建一个允许类似以下内容的修饰符:
How would it be possible to create a modifier that allows something like:
LabelView()
.font1(.callout)
.font2(.body)
我正在尝试学习如何以苹果公司使用Swift UI进行声明式编写API,但是似乎文档还不完善.我曾尝试创建某种 ViewModifier
类型,但我不太确定该怎么做,因为这需要我返回 _ModifiedContent< _,_>
也不完全知道该怎么做.基本上,可以使用声明性语法(例如内置的SwiftUI视图中的语法)来修改视图的属性.
I'm trying to learn how to write API's in the declarative nature that Apple is pushing with Swift UI but it seems like documentation isn't complete on this. I've tried creating some sort of ViewModifier
type but I'm not really sure what I need to do with this, since it required I return _ModifiedContent<_, _>
and not exactly sure how to do this. Basically, is it possible to modify the properties of a view using a declarative syntax like the ones in the built in SwiftUI views.
推荐答案
正如dfd在评论中链接到的那样,您可以创建使用Apple提供的修饰符的自定义修饰符.您也可以 创建自己的方法来修改 var
s.
As dfd linked to in the comments, you can create custom modifiers that use apple's provided modifiers. You can also create your own methods that modify var
s though.
注意:您不能在此处使用变异方法,因为函数构建器会返回不可变的值.您会收到一个编译器错误.您需要制作一份 self
的副本并将其退回.
Note: You can't use mutating methods here because function builders return immutable values. You'll get a compiler error. You need to make a copy of self
and return that.
extension LabelView {
func font1(_ font1: Font) -> Self {
var copy = self
copy.font1 = font1
return copy
}
}
您还可以创建使用密钥路径更新变量的通用版本:
You can also create a generic version that updates variables using a keypath:
extension View {
func modifying<T>(_ keyPath: WritableKeyPath<Self, T>, value: T) -> Self {
var copy = self
copy[keyPath: keyPath] = value
return copy
}
}
两种版本的用法:
struct LabelView: View {
var font1: Font = .headline
var font2: Font = .body
var body: some View { ... }
}
LabelView()
.modifying(\.font2, value: .callout)
.font1(.largeTitle)
结果如下:
这篇关于为Swift UI视图创建自定义修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!