设备方向后的 UIView 位置 [英] UIView Position After Device Orientation
问题描述
考虑将一个视图作为子视图添加到主视图中,如下所示:
Consider that a view is added as subview to the main view as follows:
override func viewDidLoad()
{
super.viewDidLoad()
let subview = UIView(frame: CGRect(x: 150, y: 350, width: 20, height: 20))
subview.backgroundColor = UIColor.blue
self.view.addSubview(subview)
}
当设备从纵向变为横向时,默认行为是子视图以一种方式移动,它与设备左上角的水平和垂直距离保持不变.我怎样才能改变它,使其与设备中心的水平和垂直距离保持不变?谢谢
When the device goes from portrait to landscape, the default behaviour is that the subview is moved in a way that its horizontal and vertical distance from the upper left corner of the device, remain unchanged. How can i change this so that its horizontal and vertical distance from the center of the device, remain unchanged? Thank you
推荐答案
最简单的方法是为视图使用约束而不是固定框架.代码看起来像这样:
The easiest way is to use constraints instead of a fixed frame for your view. The code would look something like this:
override func viewDidLoad()
{
super.viewDidLoad()
let subview = UIView()
/// You do not need to refer to self and UIColor, Swift does that for you.
subview.backgroundColor = .blue
view.addSubview(subview)
/// Do not forget the following line
subview.translatesAutoresizingMaskIntoConstraints = false
/// Create and activate your constraints in one step.
NSLayoutConstraint.activate([
/// Set the height and width of your subview
subview.heightAnchor.constraint(equalToConstant: 20),
subview.widthAnchor.constraint(equalToConstant: 20),
/// This centers the subview vertically and horizontally in the parent view
subview.centerXAnchor.constraint(equalTo: view.centerXAnchor),
subview.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
你也应该重构上面的代码,例如设置所有内容并在 viewDidLoad
中调用它的 create 方法.
Also you should refactor the code above, e.g. create method that sets up everything and call it inside of viewDidLoad
.
这篇关于设备方向后的 UIView 位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!