0

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


}
Nickkk
  • 2,261
  • 1
  • 25
  • 34
  • Have you tried adding constraints or `text.translatesAutoresizingMaskIntoConstraints = true`? – Willeke Jun 27 '23 at 23:38
  • Why didn't I think of that? Adding constraints when layout doesn't work as expected should be the first thing to try. In my case, as you suggested, setting `text.translatesAutoresizingMaskIntoConstraints = true` was enough to prevent the automatic hugging of the text. Thanks! Please add your suggestions as an answer and I'll accept it. – Nickkk Jun 28 '23 at 16:15

1 Answers1

0

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

Willeke
  • 14,578
  • 4
  • 19
  • 47