使用条件运算符搭配.labelStyle修饰符出现报错问题
问题:动态切换LabelStyle触发编译错误
需求:当isTextVisible为false时,Label显示标题和图标;当isTextVisible为true时,仅显示图标。但使用三元运算符给.labelStyle赋值时,出现编译错误:"Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure"
原代码如下:
import SwiftUI struct ContentView: View { @State private var text = "" @State private var isTextVisible: Bool = false var body: some View { HStack { Button { withAnimation { isTextVisible.toggle() text = "" } } label: { Label(isTextVisible ? "Delete" : "Add", systemImage: isTextVisible ? "minus.circle.fill" : "plus.circle.fill") .labelStyle(isTextVisible ? .iconOnly : .titleAndIcon) // 触发错误的行 .symbolRenderingMode(.palette) .foregroundStyle(.white, isTextVisible ? .red : .green) } if isTextVisible { TextField("", text: $text) } } } }
解决方法
问题根源:LabelStyle的.iconOnly和.titleAndIcon是不同的具体类型,Swift无法通过三元运算符推断出统一的LabelStyle类型,导致类型不匹配错误。
方法一:条件分支创建Label
通过@ViewBuilder分别创建两种状态下的Label,各自应用对应的LabelStyle:
import SwiftUI struct ContentView: View { @State private var text = "" @State private var isTextVisible: Bool = false var body: some View { HStack { Button { withAnimation { isTextVisible.toggle() text = "" } } label: { @ViewBuilder var dynamicLabel: some View { if isTextVisible { Label("Delete", systemImage: "minus.circle.fill") .labelStyle(.iconOnly) } else { Label("Add", systemImage: "plus.circle.fill") .labelStyle(.titleAndIcon) } } dynamicLabel .symbolRenderingMode(.palette) .foregroundStyle(.white, isTextVisible ? .red : .green) } if isTextVisible { TextField("", text: $text) } } } }
方法二:自定义动态LabelStyle
创建一个自定义的DynamicLabelStyle,通过传入的布尔值控制显示方式:
import SwiftUI struct DynamicLabelStyle: LabelStyle { let showText: Bool func makeBody(configuration: Configuration) -> some View { if showText { Label(configuration.title, icon: configuration.icon) .labelStyle(.titleAndIcon) } else { Label(configuration.title, icon: configuration.icon) .labelStyle(.iconOnly) } } } // 扩展LabelStyle方便调用 extension LabelStyle where Self == DynamicLabelStyle { static func dynamic(showText: Bool) -> DynamicLabelStyle { DynamicLabelStyle(showText: showText) } } struct ContentView: View { @State private var text = "" @State private var isTextVisible: Bool = false var body: some View { HStack { Button { withAnimation { isTextVisible.toggle() text = "" } } label: { Label(isTextVisible ? "Delete" : "Add", systemImage: isTextVisible ? "minus.circle.fill" : "plus.circle.fill") .labelStyle(.dynamic(showText: !isTextVisible)) // isTextVisible为false时显示文本 .symbolRenderingMode(.palette) .foregroundStyle(.white, isTextVisible ? .red : .green) } if isTextVisible { TextField("", text: $text) } } } }
内容的提问来源于stack exchange,提问作者0x1801ce
相关产品推荐
相关产品推荐

