ios 为什么我不能在 Swift 中更改视图的帧大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30171366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:57:33  来源:igfitidea点击:

Why can't I change the view's frame size in Swift?

iosswiftuiviewframe

提问by kalafun

So this is the weirdest thing I came across ever.

所以这是我遇到的最奇怪的事情。

I add a simple UIViewon top of an UIViewon an UIViewController. I change the size to 200 x 200 and then I want to change the UIView's size by placing this line of code inside the viewDidLoadmethod:

我添加了一个简单UIView的的顶部UIViewUIViewController。我将大小更改为 200 x 200,然后我想UIView通过在viewDidLoad方法中放置这行代码来更改的大小:

self.gameBackgroundView.frame.size.height = 10

which seems perfectly normal in Swift. Though, nothing happens. I can change the color, corner radius etc...

这在 Swift 中似乎很正常。虽然,什么也没有发生。我可以更改颜色、圆角半径等...

EDIT:

编辑:

I have also deleted all constraints from that view and it still does not work.

我还从该视图中删除了所有约束,但它仍然不起作用。

回答by kalafun

Ok, So I found a solution here on stack ..

好的,所以我在堆栈上找到了一个解决方案..

Change frame programmatically with auto layout

使用自动布局以编程方式更改框架

The correct answer, that works is, that:

有效的正确答案是:

  1. I need to create an IBOutlet of my heightConstraint
  2. Change the value of that constraint accordingly
  1. 我需要创建一个高度约束的 IBOutlet
  2. 相应地更改该约束的值

Thank you all!

谢谢你们!

回答by Victor Sigler

It is because of Auto Layout, however, you could do it after Auto Layout is done its work or change constraints of it. Set it your framein your viewDidAppear()instead. It should work.

这是因为自动布局,但是,您可以在自动布局完成其工作或更改其约束后执行此操作。将其设置为您frameviewDidAppear()。它应该工作。

I hope this helps you.

我希望这可以帮助你。

回答by Carlos Norena

Try this code, it will work on any device

试试这个代码,它可以在任何设备上运行

let BackImage = UIImage(named: "[email protected]")!

var imageView: UIImageView!

override func loadView() {

    super.loadView()
    self.imageView = UIImageView(frame: CGRectZero)
    self.imageView.contentMode = .ScaleAspectFill
    self.imageView.image = BackImage
    self.view.insertSubview(imageView, atIndex: 0)

}

override func viewDidLayoutSubviews() {

    super.viewDidLayoutSubviews()
    self.imageView.frame = self.view.bounds

}