SwiftUI的 Date.FormatStyle在备用日历下不起作用
我正在尝试让SwiftUI使用 Date.FormatStyle 在两种日历中格式化日期,但一直没能成功。我到底哪里出错了?下面给出一个最小的示例:
import SwiftUI
struct ContentView: View {
let date = Date()
var islamicStyle: Date.FormatStyle {
var style = Date.FormatStyle(date: .numeric, time: .omitted)
style.calendar = Calendar(identifier: .islamicUmmAlQura)
return style
}
var body: some View {
VStack {
Text(date, format: islamicStyle)
Text(date, format: .dateTime.year().month().day())
}
.padding()
}
}
两个输出都使用格里高利历(我的系统日历)——我到底做错了什么?Xcode 26.4。
顺便说一句:我知道我可以使用一个 DateFormatter,并手动指定一个固定的日期格式(确实会遵循该日历),但使用 Date.FormatStyle 的好处是它也会尊重诸如区域设置之类的其他用户偏好。
解决方案
SwiftUI Text 的格式化似乎会把日期格式中的日历覆盖为SwiftUI环境中的日历。因此,与其设定 Date.FormatStyle.calendar,不如按下面这样设定SwiftUI的环境日历:
Text(date, format: Date.FormatStyle(date: .numeric, time: .omitted))
.environment(\.calendar, Calendar(identifier: .islamicUmmAlQura))
当然,如果你想在SwiftUI之外使用该格式,仍然应该设定 Date.FormatStyle.calendar。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。