UIContainerView stops receiving touch after changing frame

Viewed 105

UIContainerView to display a view controller:

enter image description here

Now I am tying to make it full screen when user tap full screen button with this code :

@IBAction func fullscreen(_ sender: Any) {
        view.goFullscreen()
    }

extension CGAffineTransform {

    static let ninetyDegreeRotation = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
}

extension UIView {

    var fullScreenAnimationDuration: TimeInterval {
        return 0.15
    }

    func minimizeToFrame(_ frame: CGRect) {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.identity)
            self.frame = frame
        }
    }


    func goFullscreen() {
        UIView.animate(withDuration: fullScreenAnimationDuration) {
            self.layer.setAffineTransform(.ninetyDegreeRotation)
            self.frame = UIScreen.main.bounds

        }
    }
}

Making view full screen works fine but when viewcontroller is full screen the view stop receiving touch. This happens when I add constraints to the view controller, but when I remove it it works fine. Why this happens and how can I able to both set constraint and receiving touch?

enter image description here

1 Answers

Here is a playground illustrating how you can apply the transform to detected touch point in the superview:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    private let redView = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(redView)
        redView.translatesAutoresizingMaskIntoConstraints = false
        redView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        redView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        redView.centerXAnchor.constraint(equalTo: redView.superview!.centerXAnchor).isActive = true
        redView.centerYAnchor.constraint(equalTo: redView.superview!.centerYAnchor).isActive = true
        redView.backgroundColor = .red
        redView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap))
        view.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc private func tap(tapGestureRecognizer: UITapGestureRecognizer) {
        let point = tapGestureRecognizer.location(in: redView).applying(redView.transform)
        if redView.bounds.applying(redView.transform).contains(point) {
            print ("You tapped inside")
        } else {
            print("You tapped outside)")
        }
    }
}

let v = ViewController()
PlaygroundPage.current.liveView = v.view
Related