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
.clear
. – Glass