如何使用.center将子视图放在父视图的中心?

时间:2017-05-14 07:57:27

标签: ios swift center subview frames

我有两个子视图:紫色的一个属于主视图,它的语法很好用:

sSubview.center = view.center 

橙色视图属于紫色视图,并且相同的语法不能正确放置在中心。 你能看出我的错误在哪里吗?

Here is my code:

import UIKit

class ViewController: UIViewController {

var sSubview = UIView()
var sLabel = UILabel()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    view.backgroundColor = UIColor.lightGray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidLayoutSubviews() {

    createSimplestSubview()

}

// First subview

func createSimplestSubview() {
 sSubview = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width * 0.9, height: view.frame.height * 0.9))
 sSubview.backgroundColor = UIColor.purple // just for test, to make it visible
 sSubview.center = view.center // that s pretty easy!

 view.addSubview(sSubview)
 createSimplestLabel()
 }

// Second subview

func createSimplestLabel() {

    sLabel = UILabel(frame: CGRect(x: 0, y: 0, width: sSubview.frame.width * 0.3, height: sSubview.frame.height * 0.2))
    sLabel.backgroundColor = UIColor.orange // just for test, to make it visible
    sLabel.center = sSubview.center
    sLabel.text = "This label has to be centered!"
    sLabel.textAlignment = .center
    sLabel.numberOfLines = 0
    sSubview.addSubview(sLabel)

}

}

这是一个屏幕: enter image description here

2 个答案:

答案 0 :(得分:4)

尝试使用秒子视图的下一个代码:

sLabel.center = CGPoint(x: sSubview.frame.width / 2, y: sSubview.frame.height / 2)

您试图在中心放置一个标签,但是根据第一个Sbuview框架进行计算,其原点不是0.0

答案 1 :(得分:2)

更好的方法是使用convertPoint,因为代码的问题是坐标空间有时会有所不同。

sSubview.center = view.superview.convert(view.center, to: sSubview.superview)

view.center位于view.superview

的坐标空间中

sSubview.center位于sSubview.superview

的坐标空间中