【问题标题】:How do I click a button behind a full-screen UIView?如何单击全屏 UIView 后面的按钮?
【发布时间】:2020-05-02 03:46:48
【问题描述】:

我想在我的页面(UIViewController)中显示渐变效果。所以我添加了一个带有渐变背景颜色属性的UIView 作为最后一层。但是在我添加了这个UIView 之后,我不能点击按钮(当然)。我怎么解决这个问题?我必须以渐变效果显示我的页面。渐变效果图层必须位于页面上方(顶部)。

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")
    }
}

【问题讨论】:

    标签: ios swift uiview cagradientlayer


    【解决方案1】:

    使用

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

    然后

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

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 2017-11-10
      • 1970-01-01
      • 2016-02-19
      相关资源
      最近更新 更多