Search code examples
cocoaavkit

NSTextField frame automatically hugs content when superview is AVPlayerView.contentOverlayView


I need to manually set the frame of a NSTextField, but it seems that when added to AVPlayerView.contentOverlayView the frame gets resized so that it hugs the text.

enter image description here

This doesn't happen when the text field is added to a simple NSView instead.

enter image description here

Is this a bug? Is there a workaround?

class ViewController: NSViewController {

    override func loadView() {
        view = NSView()
        let text = NSTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
        text.translatesAutoresizingMaskIntoConstraints = false
        text.isEditable = false
        text.backgroundColor = .red
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = .center
        text.attributedStringValue = NSAttributedString(string: "asdf", attributes: [.paragraphStyle: paragraph])
        view.addSubview(text)

        // commenting out the following 3 lines solves the issue
        let playerView = AVPlayerView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        view.addSubview(playerView)
        playerView.contentOverlayView!.addSubview(text)

        // uncommenting the following 5 lines also solves the issue, but the wrong text field frame is briefly visible before it resizes to the correct width
//        DispatchQueue.main.async {
//            print(text.frame)
//            text.frame.size.width = 200
//            text.removeConstraints(text.constraints)
//        }
    }


}

Solution

  • Without constraints, autolayout does what it wants. Add constraints or let NSView translate the default autoresizing mask into constraints.