找到X轴的中间放置标签Swift Xcode 6

时间:2014-12-14 04:43:01

标签: xcode swift label

我在Swift中有一个标签,我是以编程方式制作的。我试图将此标签放在x轴的中间,而不管设备的屏幕尺寸如何。我该怎么做?

    var label = UILabel(frame: CGRectMake(0, 0, 400, 50))
    label.textColor = UIColor.whiteColor()
    label.font = UIFont(name: label.font.fontName, size: 50)
    label.textAlignment = NSTextAlignment.Center
    label.text = "My label is cool"
    self.view?.addSubview(label)

2 个答案:

答案 0 :(得分:4)

使用UIScreen.mainScreen()。bounds.width和height如下:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let label = UILabel(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    label.textColor = UIColor.blackColor()
    label.font = UIFont(name: label.font.fontName, size: 50)
    label.textAlignment = NSTextAlignment.Center
    label.text = "My label is cool"
    self.view?.addSubview(label)

}

答案 1 :(得分:0)

仅x轴的中间是不够的。你应该决定它应该在y轴上的哪个位置。

这是一个将标签放在x和y中间(即在视图中间)的示例:

func placeTheLabelAtCenterOfView(view: UIView, withRect rect: CGRect, andText text: String) {
    let label = UILabel(frame: rect)
    label.textColor = UIColor.whiteColor()
    label.font = UIFont(name: label.font.fontName, size: 50)
    label.textAlignment = NSTextAlignment.Center
    label.text = text

    // Disable automatic translation of constraints
    label.setTranslatesAutoresizingMaskIntoConstraints(false)

    // Create the needed constraints
    let horizontalConstraint = NSLayoutConstraint(
        item: label,
        attribute: NSLayoutAttribute.CenterX,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.CenterX,
        multiplier: 1,
        constant: 0
    )

    let verticalConstraint = NSLayoutConstraint(
        item: label,
        attribute: NSLayoutAttribute.CenterY,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.CenterY,
        multiplier: 1,
        constant: 0
    )

    // Add the subView (before adding the constraints)
    view.addSubview(label)

    // Add the constraints
    view.addConstraints([
        horizontalConstraint,
        verticalConstraint,
        ])
}