多种类型的重用扩展
我试图在多种类型的扩展中重复使用一项功能,但是目前我在类型上遇到了困难。我的代码如下:
struct TitleStyle: ViewModifier {
func body(content: Content) -> some View {
content.font(.system(size: 34, weight: .bold))
}
}
protocol TextStyle {
associatedtype V: View
func textStyle<Style: ViewModifier>(_ style: Style) -> V
}
extension TextStyle where Self: View {
func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
ModifiedContent(content: self, modifier: style)
}
}
extension Text: TextStyle {}
extension TextEditor: TextStyle {}
这将使我能够创建一个可重复使用的组件,如下所示:
func ExpandingTextEditor<Style: ViewModifier>(text: Binding<String>, style: Style) -> some View {
ZStack {
TextEditor(text: text)
.textStyle(style)
Text(text.wrappedValue)
.textStyle(style)
.opacity(0)
.padding(.all, 8)
}
}
在我设法进入此阶段的堆栈溢出上的类似问题上,我遇到了错误:
- “文本不符合协议TextStyle“
- ” TextEditor不符合协议TextStyle“
我缺少什么?
I am attempting to reuse a piece of functionality in an extension across multiple types but I'm currently having a difficult time with the types. My code is as follows:
struct TitleStyle: ViewModifier {
func body(content: Content) -> some View {
content.font(.system(size: 34, weight: .bold))
}
}
protocol TextStyle {
associatedtype V: View
func textStyle<Style: ViewModifier>(_ style: Style) -> V
}
extension TextStyle where Self: View {
func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
ModifiedContent(content: self, modifier: style)
}
}
extension Text: TextStyle {}
extension TextEditor: TextStyle {}
This would allow me to create a reusable component as follows:
func ExpandingTextEditor<Style: ViewModifier>(text: Binding<String>, style: Style) -> some View {
ZStack {
TextEditor(text: text)
.textStyle(style)
Text(text.wrappedValue)
.textStyle(style)
.opacity(0)
.padding(.all, 8)
}
}
Looking at similar questions to mine on Stack Overflow I've managed to get to this stage but I am getting the errors:
- "Text does not conform to protocol TextStyle"
- "TextEditor does not conform to protocol TextStyle"
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要扩展到
view < / code>,
或者只需要限制到特定视图:
用Xcode 13.3 / ios测试15.4
You just need extension to
View
, likeor if you want to limit to only specific views:
Tested with Xcode 13.3 / iOS 15.4