SwiftUI中无需DatePickerStyle修改DatePicker字体与字重的方法
问题解答
不存在无需借助DatePickerStyle的直接方法来修改SwiftUI DatePicker的字体和字重。默认情况下,SwiftUI的DatePicker(尤其是紧凑样式)的内部文本元素是系统封装的,.font()修饰符只能作用于DatePicker的外部容器,无法穿透到内部的日期显示文本上,这就是你代码里该修饰符无效的原因。
下面提供两种可行的解决思路:
1. 自定义DatePickerStyle
通过实现自定义DatePickerStyle,可以完全控制DatePicker的显示内容,包括字体设置:
struct CustomDatePickerStyle: DatePickerStyle { func makeBody(configuration: Configuration) -> some View { Button(action: { configuration.presentationMode.wrappedValue.toggle() }) { Text(configuration.date.formatted(date: .abbreviated, time: .omitted)) .font(.custom("HelveticaNeue-Thin", size: 10, relativeTo: .caption)) .foregroundColor(.primary) } .popover(isPresented: configuration.presentationMode) { DatePicker("", selection: configuration.$selection, displayedComponents: .date) .datePickerStyle(.graphical) .padding() } } } // 使用方式 DatePicker("Start date", selection: Binding(get:{goal.startDate!},set:{goal.startDate = $0}), displayedComponents: .date ) .datePickerStyle(CustomDatePickerStyle()) .labelsHidden()
2. 用UIViewRepresentable包装UIDatePicker
借助UIKit的UIDatePicker可以直接设置字体,再包装成SwiftUI组件使用:
struct UIKitDatePicker: UIViewRepresentable { @Binding var date: Date let displayedComponents: UIDatePicker.Component func makeUIView(context: Context) -> UIDatePicker { let picker = UIDatePicker() picker.datePickerMode = .date picker.addTarget(context.coordinator, action: #selector(Coordinator.dateChanged), for: .valueChanged) // 直接设置字体 picker.font = UIFont(name: "HelveticaNeue-Thin", size: UIFont.captionSize) picker.preferredDatePickerStyle = .compact return picker } func updateUIView(_ uiView: UIDatePicker, context: Context) { uiView.date = date } func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject { let parent: UIKitDatePicker init(_ parent: UIKitDatePicker) { self.parent = parent } @objc func dateChanged(_ sender: UIDatePicker) { parent.date = sender.date } } } // 使用方式 UIKitDatePicker(date: Binding(get:{goal.startDate!},set:{goal.startDate = $0}), displayedComponents: .date)
内容的提问来源于stack exchange,提问作者quaternionboy
相关产品推荐
相关产品推荐

