我遇到了SwiftUI和ScrollView的问题。当我在滚动视图中有一个带有混合模式属性的子视图时,混合不会影响滚动视图的内容。但是,如果我将同一项目放在堆栈中,则会影响背景。
我试图将混合模式直接应用到滚动视图,但是由于子视图中还有其他项没有被混合,因此将其弄乱了。 这里是一个示例来说明问题。这样,您可以在“堆栈”中看到渐变混合,但在滚动视图中看不到。
let mode: BlendMode = .overlay
func item(_ num: Int) -> some View {
return AnyView(
ZStack {
Rectangle()
.fill( LinearGradient(gradient: Gradient(colors: [Color.blue, Color.black]), startPoint: .top, endPoint: .bottom))
.frame(width: 100, height: 100)
.blendMode(mode)
Text("Number = \(num)")
.font(.headline)
.foregroundColor(Color.white)
}
)
}
struct ContentView: View {
var body: some View {
ZStack {
Rectangle()
.fill(RadialGradient(gradient: Gradient(colors: [Color.black, Color.red]), center: .topLeading, startRadius: 200, endRadius: 800))
HStack (spacing: 50) {
VStack (spacing: 50) {
ForEach((1...5).reversed(), id: \.self) {
item($0)
}
}
ScrollView {
VStack (spacing: 50) {
ForEach((1...5).reversed(), id: \.self) {
item($0)
}
}
}
//.blendMode(mode)
/*
blendMode for item() in ScrollView does not work.
Uncomment blendMode modifier above to get gradient blend, but text is not correct
*/
}
}
}
}
我还尝试将黑色到红色的Rectangle用作Scrollview的背景,但这也不能解决问题。
ScrollView {
VStack (spacing: 50) {
ForEach((1...5).reversed(), id: \.self) {
item($0)
}
}
}
.background(
Rectangle()
.fill(RadialGradient(gradient: Gradient(colors: [Color.black, Color.red]), center: .topLeading, startRadius: 200, endRadius: 800))
)
在下面的图片中,我想要的外观在左侧的VStack中。
No blend mode modifier on ScrollView
Blend mode modifier applied to Scrollview
有人知道如何解决这个问题吗?
我唯一能想到的,似乎很棘手的事情是,基本上是创建两个z-stacked的滚动视图,然后将Blend应用于仅需要它的滚动视图,然后将未混合的项目放在最上面的滚动视图中。
但是,我认为这不可行,因为我看不到在两个滚动视图之间同步滚动的方法。
答案 0 :(得分:0)
我遇到了类似的问题,通过实验,当设置了混合模式的SwiftUI View
直接位于UIHostingView
(例如{ {1}}。
您可以通过将另一个SwiftUI视图放置在滚动视图内部的混合模式下来获得正确的混合,例如
ScrollView
这不能完全解决您的示例中的问题,因为两个背景并不完全对齐,但是在滚动视图占据屏幕的情况下可能会有所帮助。
似乎在滚动视图中添加ScrollView {
ZStack {
Rectangle()
.fill(RadialGradient(gradient: Gradient(colors: [Color.black, Color.red]), center: .topLeading, startRadius: 200, endRadius: 800))
VStack (spacing: 50) {
ForEach((1...5).reversed(), id: \.self) {
item($0)
}
}
}
}
会将其添加到.background
的下方,而不是ScrollView
中层次结构的底部,这就是为什么它似乎没有修复它。
我的问题是在ScrollView
行中(由List
支持),并且在UITableView
内的项目上设置了明确的背景对此有所帮助。希望这将使您/其他人朝正确的方向前进。