Search code examples
swiftnsviewnsbuttoncatransform3dtarget-action

NSButton not callable after CATransform3DMakeTranslation


I have a strange issue never seen on iOS but present on macOS Swift development.

I have a NSButton which is added with an addSubview method to a custom NSView. The button has a target function. It is impossible to click on this button when it's added to the customView. If I add it to the global "view" works fine directly.

Any idea why this could be?

//Infos View
self.infosView.wantsLayer = true
self.infosView.layer?.backgroundColor = NSColor.darkGray.cgColor

self.view.addSubview(self.infosView)

 //TestButton
let myButtonRect = CGRect(x: 100, y: 100, width: 200, height: 200)
self.testButton = NSButton.init(frame: myButtonRect)

// !!!!
// this line doesn't work
// !!!!
self.infosView.addSubview(testButton)

// !!!!
// but this line works fine
// !!!!
self.view.addSubview(testButton)

self.testButton.target = self
self.testButton.action = #selector(ViewController.printSomething)

Update : The testButton is not clickable after a CATransform

self.infosView.layer?.transform = CATransform3DMakeTranslation(500, 0, 0)

Doesn't work after this..


Solution

  • I paste here the answer of this question. The problem was the constraints of the NSView.

    1- Create a NSLayoutConstraints() variable

    2- Set the constraints of the NSView

    self.infosView.translatesAutoresizingMaskIntoConstraints = false
            self.leadingConstraint = self.infosView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: -500)
            self.leadingConstraint.isActive = true
            self.infosView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
            self.infosView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0, constant: 500).isActive = true
            self.infosView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0, constant: (NSScreen.main?.frame.height)!).isActive = true
    

    3 - Then when I want to update the NSView which contains the NSButton

    self.leadingConstraint.constant = 0
    
    runAnimation(duration: 0.5, {
        self.testButton.superview?.layoutSubtreeIfNeeded()
    
        self.infosViewOpened = true
    
    })