简体   繁体   English

Swift ui macos 背景透明TextField

[英]Swift ui macos background transparent TextField

在此处输入图片说明

As you can see from the image I have a TextField and after list .正如您从图像中看到的,我有一个TextField和 after list

The list has a transparent background, I'm using .listStyle(SidebarListStyle()) .该列表具有透明背景,我使用的是.listStyle(SidebarListStyle())

But how do I get a transparent background where the TextField is located.但是如何获得TextField所在的透明背景。

Code:代码:

VStack(alignment: .leading, spacing: 0) {

    TextField("Username", text: $username)
    .padding(.leading, 20)
    .padding(.trailing, 20)
    .background(
        RoundedRectangle(cornerRadius: 5)
            .fill(Color.white.opacity(0.3)
        )
        .padding(.leading, 20)
        .padding(.trailing, 20)
    )
    .padding(.top)
    .padding(.bottom)

    List(restaurants) { restaurant in
        RestaurantRow(restaurant: restaurant)
    }.listStyle(SidebarListStyle())

}.padding(0)
.frame(width: 400.0, height: 400.0, alignment: .top)

You need visual effect view in background (it is used by default for sidebar styled lists)您需要背景中的视觉效果视图(它默认用于侧边栏样式列表)

Demo prepared & tested with Xcode 11.4 / macOS 10.15.6使用 Xcode 11.4 / macOS 10.15.6 准备和测试的演示

演示

struct VisualEffectView: NSViewRepresentable {
    func makeNSView(context: Context) -> NSVisualEffectView {
        let view = NSVisualEffectView()

        view.blendingMode = .behindWindow    // << important !!
        view.isEmphasized = true
        view.material = .appearanceBased
        return view
    }

    func updateNSView(_ nsView: NSVisualEffectView, context: Context) {
    }
}

and put it to needed area, in this case below TextField并将其放在需要的区域,在这种情况下位于TextField下方

    TextField("Username", text: $username)
    .padding(.leading, 20)
    .padding(.trailing, 20)
    .background(
        RoundedRectangle(cornerRadius: 5)
            .fill(Color.white.opacity(0.3)
        )
        .padding(.leading, 20)
        .padding(.trailing, 20)
    )
    .padding(.top)
    .padding(.bottom)
    .background(VisualEffectView())

You could use on the background Color.white.opacity(0.01) or Color.clear in your case:您可以在背景上使用 Color.white.opacity(0.01) 或 Color.clear 在您的情况下:

     .background(
       RoundedRectangle(cornerRadius: 5)
       .fill(Color.white.opacity(0.01))
     

or或者

      .background(
        RoundedRectangle(cornerRadius: 5)
        .fill(Color.clear))
   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM