如何通过设置frame属性来移动或调整NSView的大小? [英] How to move or resize an NSView by setting the frame property?

查看:253
本文介绍了如何通过设置frame属性来移动或调整NSView的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在情节提要中创建了NSView.在这种情况下,它是NSTextField.在NSViewControllerviewDidLoad()方法中,我想有条件地调整NSTextField的大小和位置,但是设置框架没有效果.

I created the NSView in a storyboard. In this case, it is an NSTextField. In the NSViewController's viewDidLoad() method, I want to conditionally resize and reposition the NSTextField, but setting the frame has no effect.

例如:

class ViewController: NSViewController {

    @IBOutlet var label: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        label.frame = NSRect(x: 0, y: 0, width: 200, height: 17)
        label.setNeedsDisplay()
    }
}

加载视图时,标签仍然具有其在界面构建器中设置的原始框架,而不是新设置的框架.

When the view loads, the label still has its original frame as set in interface builder, and not the newly set frame.

一个人如何以编程方式移动/调整标签大小?

How does one programmatically move/resize the label?

推荐答案

自动布局系统是这里的罪魁祸首.设置框架时,自动布局系统会覆盖该框架,以重新建立情节提要中设置的隐式约束.

The autolayout system is the culprit here. When you set the frame, the autolayout system overrides that to re-establish the implicit constraints set in the storyboard.

将标签的translatesAutoresizingMaskIntoConstraints属性设置为true.这告诉自动布局系统应创建一个 new 套自动布局约束,这些约束应满足您设置的新框架:

Set the translatesAutoresizingMaskIntoConstraints property of the label to true. This tells the autolayout system that it should create a new set of autolayout constraints that satisfy the new frame you've set:

class ViewController: NSViewController {

    @IBOutlet var label: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        label.frame = NSRect(x: 0, y: 0, width: 200, height: 17)
        label.translatesAutoresizingMaskIntoConstraints = true
        label.setNeedsDisplay()
    }
}

这篇关于如何通过设置frame属性来移动或调整NSView的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆