UILabel居中顯示的方法

流火行者發表於2015-03-23

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

 

 

 

 

相關文章