简体   繁体   中英

How to make SwiftUI view transparent or semi-transparent inside an UIView?

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

在此处输入图片说明

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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