SwiftUI:超过 4 个组合的文本视图不能与视图修饰符一起使用
Posted
技术标签:
【中文标题】SwiftUI:超过 4 个组合的文本视图不能与视图修饰符一起使用【英文标题】:SwiftUI: More than 4 combined Text Views not working with view modifiers 【发布时间】:2021-06-21 01:54:05 【问题描述】:所以我想在 SwiftUI 中将多个文本视图与不同的颜色组合起来,但是在添加了第 5 个文本视图并为前景添加了一个视图修饰符之后它变得非常复杂,然后它给了我奇怪的错误并说要分解查看不同的子视图。
struct dialogueBox: View
var body: some View
GroupBox
Group
Text("this").foregroundColor(.pink)
+ Text(" code ")
+ Text("works")
+ Text(" well ").foregroundColor(.green)
.font(.footnote)
Group
Text("but").foregroundColor(.pink)
+ Text(" this ")
+ Text("code")
+ Text(" does ").foregroundColor(.green)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
.font(.footnote)
【问题讨论】:
我以前见过这个问题,但找不到解决方案……但在 ios 15 中,您可以改用 AttributedString:***.com/a/67889368/14351818 【参考方案1】:您可以为文本创建一个 var,然后在 Group 中使用它。
struct DialogueBox: View
var body: some View
GroupBox
Group
Text("this").foregroundColor(.pink)
+ Text(" code ")
+ Text("works")
+ Text(" well ").foregroundColor(.green)
.font(.footnote)
Group
textView
.font(.footnote)
private var textView: Text
Text("but").foregroundColor(.pink)
+ Text(" this ")
+ Text("code")
+ Text(" does ").foregroundColor(.green)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
【讨论】:
这非常有效,而且是一个非常聪明的方法,谢谢!【参考方案2】:在 macos 12.beta、xcode 13.beta、target ios 14.7 和 macCatalyst 12 上运行良好。在 macOS 12 和 iPhone ios 14.7 上测试。
import SwiftUI
@main
struct TestApp: App
var body: some Scene
WindowGroup
ContentView()
struct ContentView: View
var body: some View
DialogueBox()
struct DialogueBox: View
var body: some View
GroupBox
Group
Text("this").foregroundColor(.pink)
+ Text(" code ")
+ Text("works")
+ Text(" well ").foregroundColor(.green)
.font(.footnote)
Group
Text("but").foregroundColor(.pink)
+ Text(" this ")
+ Text("code")
+ Text(" does ").foregroundColor(.green)
+ Text(" not ").foregroundColor(.blue)
+ Text(" for some reason ").foregroundColor(.red)
.font(.footnote)
Group
Text("This ").foregroundColor(.pink)
+ Text(" is ")
+ Text("more")
+ Text(" stuff ").foregroundColor(.green)
+ Text(" and ").foregroundColor(.blue)
+ Text(" longer ").foregroundColor(.red)
+ Text(" still ").foregroundColor(.green)
+ Text(" more ").foregroundColor(.blue)
+ Text(" is more ")
+ Text(" more ").foregroundColor(.red)
+ Text(" and more ").foregroundColor(.blue)
.font(.footnote)
【讨论】:
以上是关于SwiftUI:超过 4 个组合的文本视图不能与视图修饰符一起使用的主要内容,如果未能解决你的问题,请参考以下文章