0
votes

Despite the SwiftUI view has opacity set to 0.5 after it added to an UIView it still has a solid color. If you look closely, you can see the SwiftUI view's white background at the top corners for rectangular below.

The code below adds a UILabel and a SwiftUI rectangular view into the root view, the rectangular has an opacity of 0.5 so it supposes to see through the text "Test" behind it however it looks like having an opaque background.

I have also tried to set the background color of the parent view of the SwiftUI view instance to color clear, however,

Is it possible to make SwiftUI view transparent or semi-transparent inside an UIView?

import UIKit
import SwiftUI

import PlaygroundSupport

struct Foo: View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 18)
                .fill(Color.red)
        }
        .background(Color.red)
        .opacity(0.5)
    }
}

class ViewController:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel()
        label.text = "TEST"
        
        view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
        
        let fooView = Foo()
        let controller = UIHostingController(rootView: fooView)
        let subview = controller.view!
        
        view.addSubview(subview)
        view.backgroundColor = .clear
        subview.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            
            subview.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            subview.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            
            subview.widthAnchor.constraint(equalToConstant: 100),
            subview.heightAnchor.constraint(equalToConstant: 100)
        ])
    }
}

let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true

enter image description here

1
Does this answer your question stackoverflow.com/a/63745596/12299030?Asperi
Thanks @Asperi but in my case, the Card SwiftUI view is inside an UIKit UIView.Glass
@Asperi I added a reproducible playground snippet for the issue.Glass
and Yes, that answer hint me for changing the background to .clear.Glass

1 Answers

2
votes

Because "every hosting controller view by default is opaque" so adding the following to the SwiftUI view solves the issue.

let fooView = Foo()
let controller = UIHostingController(rootView: fooView)
let subview = controller.view!
        
subview.backgroundColor = .clear // <--- THIS LINE

REFERENCE How can I make a background color with opacity on a Sheet view?