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
Why can't I change the view's frame size in Swift?
提问by kalafun
So this is the weirdest thing I came across ever.
所以这是我遇到的最奇怪的事情。
I add a simple UIView
on top of an UIView
on 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 viewDidLoad
method:
我添加了一个简单UIView
的的顶部UIView
上UIViewController
。我将大小更改为 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:
有效的正确答案是:
- I need to create an IBOutlet of my heightConstraint
- Change the value of that constraint accordingly
- 我需要创建一个高度约束的 IBOutlet
- 相应地更改该约束的值
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 frame
in your viewDidAppear()
instead. It should work.
这是因为自动布局,但是,您可以在自动布局完成其工作或更改其约束后执行此操作。将其设置为您frame
的viewDidAppear()
。它应该工作。
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
}