Programmatically Setting AutoresizingMask to NSView Object

563 views Asked by At

I wonder why it always fails whenever I try to set the autoresizingMask to an NSView object programmatically? In the following lines of code, I have a tiny, blue NSVIew object (topLeftView) set at the top-left corner of its parent container.

class ViewController: NSViewController {
    // MARK: - IBOutlet
    @IBOutlet weak var panView: PanView!

    override func viewDidLoad() {
        super.viewDidLoad()

        makeImageContainer(point: CGPoint.zero)
    }

    func makeViewContainer(point: CGPoint) {
        let myView = NSView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 150.0, height: 150.0))
        myView.wantsLayer = true
        if let myLayer = myView.layer {
            myLayer.backgroundColor = NSColor.orange.cgColor
        }
        panView.addSubview(myView) // panView is an IBOutlet-connected `NSView` object.

        /* tiny, blue `NSView` object */
        let topLeftView = NSView(frame: CGRect(origin: CGPoint(x: 0.0, y: 150.0 - 6.0), size: CGSize(width: 6.0, height: 6.0)))
        topLeftView.wantsLayer = true
        topLeftView.autoresizingMask = [.minXMargin, .maxYMargin]
        if let layer = topLeftView.layer {
            layer.backgroundColor = NSColor.blue.cgColor
        }
        myView.addSubview(topLeftView)
    }
}

enter image description here

So it has minXMargin and maxYMargin autoresizingMasks.

Now, I want to click on a push button to resize this orange NSView container object to see if the tiny, blue NSView object will stick at the top-left corner.

@IBAction func testClicked(_ sender: NSButton) {
    for i in 0..<panView.subviews.count {
        let subView = panView.subviews[i]
        if i == 4 {
            subView.setFrameSize(CGSize(width: 200.0, height: 200.0))
        }
    }
}

enter image description here

And the tiny guy has moved by 50 points to the right and 50 points to the bottom. What am I doing wrong? Thanks.

0

There are 0 answers