Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

swiftui - Swift ui macos background transparent TextField

enter image description here

As you can see from the image I have a TextField and after list.

The list has a transparent background, I'm using .listStyle(SidebarListStyle()).

But how do I get a transparent background where the TextField is located.

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

demo

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("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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...