UILabel居中显示的方法

在IB中拖出一个UIView

1  @IBOutlet weak var myView: UIView!

下面创建的UILabel是在myView中居中显示

方法1:

        var label = UILabel()
        label.text = "你好,朋友!"
        label.backgroundColor = UIColor.blueColor()
        label.sizeToFit()
        label.center = CGPointMake(CGRectGetMidX(myView.bounds), CGRectGetMidY(myView.bounds))
        myView.addSubview(label)

方法2:

1         var label = UILabel()
2         label.text = "你好,朋友!"
3         label.backgroundColor = UIColor.blueColor()
4         label.sizeToFit()
5         label.center = myView.convertPoint(myView.center, fromView: myView.superview)
6         myView.addSubview(label)

注意:以上方法中第四行代码label.sizeToFit()务必写到第五行代码之前执行,否则将不会居中显示

方法3:

通过VFL布局约束的方式

 

 1     func setAlignCenter(subView: UIView,superView:UIView) {
 2         subView.setTranslatesAutoresizingMaskIntoConstraints(false)
 3         var dic = ["superView":superView, "subView":subView]
 4         superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
 5             "V:[superView]-(<=0)-[subView]",
 6             options: NSLayoutFormatOptions.AlignAllCenterX,
 7             metrics: nil,
 8             views: dic))
 9         superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
10             "H:[superView]-(<=0)-[subView]",
11             options: NSLayoutFormatOptions.AlignAllCenterY,
12             metrics: nil,
13             views: dic))
14     }

 

 

 

 

转载于:https://www.cnblogs.com/JimmyBright/p/4359199.html

你可能感兴趣的:(UILabel居中显示的方法)