居中对齐子视图

Central align subView

我试图在另一个视图中将 UIView 居中(就像弹出视图一样),但无论我做什么,我都无法将它居中对齐!

func loadPopUpView() {
    let customView = CGRect(x: view.center.x, y: view.center.y, width: 100, height: 100)
    popUpView = UIView(frame: customView)
    popUpView.backgroundColor = UIColor.black
    view.addSubview(popUpView)

    popUpView.isHidden = false
}

我已将背景颜色更改为黑色,以便我知道它何时出现。 我不能用情节提要来做到这一点,因为它在 tableView 上进行,所以我试图以编程方式进行。 Result Image

您还需要从 x 和 y 中减去自定义视图高度和宽度的一半值,如下所示:

let customView = CGRect(x: view.center.x - 50, y: view.center.y - 50, width: 100, height: 100)

你告诉它把左上角放在中间,因此你需要让它在适当的位置得到一半的大小。

let customView = CGRect(x: view.center.x-50, y: view.center.y-50, width: 100, height: 100)

另一个解决方案是使用锚点。

customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
customView.heightAnchor.constraint(equalToConstant: 100).isActive = true
customView.widthAnchor.constraint(equalToConstant: 100).isActive = true

CGRect(x:, y:, width:, height:) 上,点 (x,y) 是原点。在 iOS 中,这是左上角。

CGRect doc:

In the default Core Graphics coordinate space, the origin is located in the lower-left corner of the rectangle and the rectangle extends towards the upper-right corner. If the context has a flipped-coordinate space—often the case on iOS—the origin is in the upper-left corner and the rectangle extends towards the lower-right corner.

所以要解决这个问题:

let width = 100.0
let height = 100.0
let customViewFrame = CGRect(x: view.center.x - width/2.0, y: view.center.y - height/2.0, width: width, height: height)

另一个解决方案是在设置框架(尤其是 width/size)后应用中心。

let customViewFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
customViewFrame = view.center