【问题标题】:Making SwiftUI views with clear backgrounds?制作具有清晰背景的 SwiftUI 视图?
【发布时间】:2021-05-13 04:39:55
【问题描述】:

我尝试了多种方法来使此处的白色背景清晰。似乎没有任何效果。

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List(0 ..< 5) { item in
                ChatMessageCell()
            }
            .listRowBackground(Color.clear)
            .background(Color.clear)
        }
    }
}

struct ChatMessageCell: View {
    var body: some View {
        HStack {
            Image(systemName: "person.crop.circle")
                .aspectRatio(1.0, contentMode: .fill)
            Text("This is a chat message of certain length to try to force a wrap in the preview.")
        }
    }
}

struct OverlayChatView_Previews: PreviewProvider {
    static var previews: some View {
        ZStack {
            Color.blue
                .ignoresSafeArea()
            OverlayChatView()
                .frame(maxWidth: 300.0, maxHeight: 300.0)
                .background(Color.clear)
        }
    }
}

很多人似乎都遇到了这个问题,有些人用非首发解决了它:

.onAppear {
    UITableView.appearance().backgroundColor = UIColor.clear
    UITableViewCell.appearance().backgroundColor = UIColor.clear
}

我可以将单个列表项单元格设置为特定的不透明背景颜色。我什至无法将OverlayChatViewList 设置为纯色,更不用说清除了。

iOS 14(模拟器,而非设备)

【问题讨论】:

  • 在 Xcode 中检查视图层次结构后,SwiftUI 仍在创建 UITableViews,似乎唯一的解决方案是设置所有表视图的外观。这意味着我们所有其他(非 SwiftUI)代码都必须显式设置其背景颜色。

标签: swiftui xcode12 xcode12.5


【解决方案1】:

ForEach包裹并设置背景颜色。

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List {
                ForEach(0 ..< 5) {  item in //<-- Here
                    ChatMessageCell()
                }
                .listRowBackground(Color.blue) //<-- Here
            }
            .background(Color.clear)
        }
    }
}

或者你也可以使用colorMultiply

struct OverlayChatView: View {
    var body: some View {
        ZStack {
            Color.clear
            List(0 ..< 5) { item in
                    ChatMessageCell()
                
            }.colorMultiply(Color.blue) //<-- Here
            .background(Color.clear)
        }
    }
}

【讨论】:

  • 我不是想把列表的背景变成蓝色,我想把它弄清楚(以便 whatever 背后的东西能通过)。跨度>
  • 但是你可以做一件事,在视图中声明一个颜色变量,然后在你需要的地方使用它。
  • 不,我不能。想象一下,如果背景是一张图片。
猜你喜欢
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多