SwiftUI中如何将Font weight作为参数传递给自定义视图组件?
解决SwiftUI视图组件传递字体权重参数无效的问题
你的问题核心是参数类型不匹配:SwiftUI的Text控件的font修饰符需要的是Font.Weight类型,而非你使用的Weight(若为UIFont.Weight则属于UIKit类型,和SwiftUI的Font.Weight不兼容)或UIFontDescriptor.TraitKey。
修正后的实现代码
首先在自定义视图中明确使用Font.Weight作为参数类型:
struct CustomTextView: View { let weight: Font.Weight // 可以给参数设置默认值,方便调用 init(weight: Font.Weight = .bold) { self.weight = weight } var body: some View { Text("需要设置权重的文本") // 通过system字体构造器传递权重参数 .font(.system(size: 16, weight: weight)) } }
调用自定义视图
在父视图中直接传入Font.Weight枚举值即可:
struct ContentView: View { var body: some View { VStack(spacing: 16) { CustomTextView(weight: .light) CustomTextView(weight: .medium) CustomTextView(weight: .bold) CustomTextView() // 使用默认的.bold权重 } } }
兼容UIKit字体权重(可选)
如果你的业务中需要使用UIKit的UIFont.Weight,可以通过类型转换适配SwiftUI:
let uiKitWeight: UIFont.Weight = .heavy let swiftUIWeight = Font.Weight(uiKitWeight) // 传递给自定义视图 CustomTextView(weight: swiftUIWeight)
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

