简体   繁体   English

如何在iOS中将屏幕上的对象居中

[英]How to center objects on screen in iOS

If I create a rectangular object for example like this: 例如,如果我创建一个矩形对象,例如:

square = UIView(frame: CGRect(x: 100, y: 100, width: 300, height: 100))
square.backgroundColor = UIColor.redColor()
view.addSubview(square)

How to position it, that it always be centered on all devices? 如何定位它,使其始终在所有设备上居中?

Rather than set the frame directly with calculation, and have to do it all over again under rotation, This can be done with autolayout. 与其直接通过计算来设置框架,而不必在旋转下重新做一遍,这可以使用自动布局完成。

Here is a complete and simple view controller subclass that adds a red subview in its centre, and works even when the screen is rotated. 这是一个完整而简单的视图控制器子类,该子类在其中心添加了一个红色子视图,即使旋转屏幕也可以使用。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupSubview()
    }

    func setupSubview() {
        let square = UIView()
        square.translatesAutoresizingMaskIntoConstraints = false
        square.backgroundColor = .redColor()
        view.addSubview(square)

        let views = ["square" : square]
        let metrics = ["width" : 300, "height" : 100]

        view.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:[square(width)]",
                options: [],
                metrics: metrics,
                views: views)
        )

        view.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "V:[square(height)]",
                options: [],
                metrics: metrics,
                views: views)
        )

        view.addConstraints([
            NSLayoutConstraint(
                item: square,
                attribute: .CenterX,
                relatedBy: .Equal,
                toItem: view,
                attribute: .CenterX,
                multiplier: 1.0,
                constant: 0.0
            ),
            NSLayoutConstraint(
                item: square,
                attribute: .CenterY,
                relatedBy: .Equal,
                toItem: view,
                attribute: .CenterY,
                multiplier: 1.0,
                constant: 0.0
            )
        ])
    }

}

Yes, it's a lot of code, but its mostly boilerplate - it only took me a few minutes to write this example. 是的,它有很多代码,但是主要是样板文件-仅花了我几分钟来编写此示例。

If you use nibs or storyboards, this becomes even easier. 如果使用笔尖或情节提要,这将变得更加容易。

xAxis = superview.frame.size.width / 2 - x.frame.size.width / 2
yAxis = superview.frame.size.height / 2 - x.frame.size.height / 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM