Search code examples
iosswiftuiviewcagradientlayer

How do I click a button behind a full-screen UIView?


I want to show a gradient effect in my page(UIViewController). So I have added an UIView with gradient background color property as a last layer. But I can't click the button(of course) after I have added this UIView. How can I solve this problem? I must show my page with gradient effect. Gradient effected layer must be above(on the top) of the page.

import UIKit

class ViewController: UIViewController {

    lazy var contentViewOutlet : UIView =
        {
            let myUiView = UIView()
            return myUiView
    }()

    lazy var myButton : UIButton =
        {
            let mybutton = UIButton()
            mybutton.setTitle("i want to be clicked :)", for: .normal)
            mybutton.backgroundColor = .green
            return mybutton
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(myButton)
        myButton.translatesAutoresizingMaskIntoConstraints = false

        myButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
        myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.2).isActive = true
        myButton.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.2).isActive = true
        myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        view.addSubview(contentViewOutlet)
        contentViewOutlet.translatesAutoresizingMaskIntoConstraints = false
        contentViewOutlet.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        contentViewOutlet.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        contentViewOutlet.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        contentViewOutlet.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        contentViewOutlet.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.view.bounds
        gradientLayer.colors = [UIColor.white.cgColor, UIColor.yellow.cgColor]
        contentViewOutlet.layer.insertSublayer(gradientLayer, at: 0)
        contentViewOutlet.alpha = 0.8
        view.layoutIfNeeded()

    }

    @objc func buttonAction(sender: UIButton!) {
        print("Button tapped")
    }
}

Solution

  • Use

    class TransView:UIView { 
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            return false
        } 
    }
    

    then

    lazy var contentViewOutlet : TransView = {
        let myUiView = TransView()
        return myUiView
    }()