输入在这里我正在尝试使用带有 LinearGradient 背景的 SwiftUI 创建一个小部件。当渐变垂直拉伸时,左侧和右侧会出现不需要的边距。我使用了 GeometryReader 和 .frame(width: geo.size.width, height: geo.size.height) 确保它填充小部件区域并应用了 .ignoresSafeArea(),但问题仍然存在。如何让渐变覆盖整个小部件而没有边距?使用containerRelativeFrame解决了我的问题,但它仅支持iOS 17+。我的目标是使其适用于 iOS 16+。
struct ExampleWidgetEntryView: View {
var entry: Provider.Entry
var body: some View {
GeometryReader { geo in
ZStack(alignment: .center) {
let colors = BackgroundColors.randomTwoColors()
LinearGradient(gradient: Gradient(colors: [
Color(colors.color1),
Color(UIColor.white.withAlphaComponent(0.8)),
Color(colors.color2)
]), startPoint: .topTrailing, endPoint: .bottomLeading)
.aspectRatio(contentMode: .fill)
.frame(width: geo.size.width, height: geo.size.height) // Make the gradient fill the widget
.ignoresSafeArea() // Ignore safe areas
VStack {
Text(entry.message)
.font(.system(size: 18))
.multilineTextAlignment(.center)
.padding()
.foregroundColor(Color(UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1.0)))
}
}
.frame(width: geo.size.width, height: geo.size.height) // Ensure ZStack fills the entire widget
}
}
}
containerBackground
设置小部件的背景。您可以删除ZStack
:
VStack {
Text("Some Message")
.font(.system(size: 18))
.multilineTextAlignment(.center)
.padding()
.foregroundColor(Color(red: 51/255, green: 51/255, blue: 51/255))
}
.containerBackground(
.linearGradient(colors: [.red, .white, .blue], startPoint: .topTrailing, endPoint: .bottomLeading),
for: .widget
)
您现有的代码将在 iOS 16 及之前的版本上按预期工作,因此如果您还想支持 iOS 16,只需添加
if #available
。