如何返回标签以便使用.labelStyle视图修饰符



问题是:我想要一个单一视图结构,它将返回一个基于枚举的Label(),该枚举将允许使用自定义字体字形以及标准的systemImageimageinits。

我有以下代码,它可以作为视图使用。但我不能对它应用.labelStyle(IconOnlyLabelStyle()),这就是我缺少的部分。

import SwiftUI
struct LabelWithColoredIcon: View {
enum LabelType {
case glyph
case systemImage
case image
}

let title: String
let icon: String
let color: Color
let type: LabelType

init(title: String, icon: String, color: Color, type: LabelType) {
self.title = title
self.icon = icon
self.color = color
self.type = type
}

var body: some View {
Label(title: { Text(title) },
icon: {
switch type {
case .glyph:
Text(icon)
.foregroundColor(color)
case .systemImage:
Image(systemName: icon)
.foregroundColor(color)
case .image:
Image(icon)
.foregroundColor(color)
}
})
}
}
struct LabelWithColoredIcon_Previews: PreviewProvider {
static var previews: some View {
LabelWithColoredIcon(
title: "Contact Groups",
icon: "🔥",
color: .purple,
type: .glyph)
}
}

我能够通过创建一个完全独立的视图,然后传递该视图的属性来实现这一点。然后,在初始化期间,在TestView中创建具有适当属性的视图。因此,它基于枚举中定义的Type进行切换。如果你需要随时更改,你需要将其设置为@ObservedObject@Publish变量,以便可以监控它们的状态。基于let声明,我假设您不需要它。

struct TestView: View {    
var body: some View {
TestLabel(title: "Hello", icon: "square.and.arrow.up.on.square.fill", labelType: .glyph, color: Color.black)
}
}
struct TestLabel: View {

let title: String
let icon: String
let labelType: LabelType
let color: Color

var body: some View {
Label(
title: { Text(title) },
icon: {
Group{
switch labelType {
case .glyph:
Text(icon)
case.systemImage:
Image(systemName: icon)
case .image:
Image(icon)
}
}.foregroundColor(color)
}
).labelStyle(IconOnlyLabelStyle())
}
}
enum LabelType {
case glyph, systemImage, image
}

最新更新