UI定位后的UIView位置

问题描述 投票:0回答:2

考虑如下将视图作为子视图添加到主视图:

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

当设备从纵向移动到横向时,默认行为是子视图的移动方式应使其与设备左上角的水平和垂直距离保持不变。如何更改此值,以使其与设备中心的水平和垂直距离保持不变?谢谢

ios swift uiview position orientation
2个回答
1
投票
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内部调用它的方法。


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.