Swift ui macos background transparent TextField

雨燕双飞 提交于 2020-12-06 09:03:34

问题


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)

回答1:


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

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



回答2:


You could use on the background Color.white.opacity(0.01) or Color.clear in your case:

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

or

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


来源:https://stackoverflow.com/questions/63661111/swift-ui-macos-background-transparent-textfield

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!