Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 中心对齐子视图_Swift_Xcode_Uiview_Subview - Fatal编程技术网

Swift 中心对齐子视图

Swift 中心对齐子视图,swift,xcode,uiview,subview,Swift,Xcode,Uiview,Subview,我试图将ui视图放在另一个视图的中心位置(就像弹出视图),但无论我做什么,我都无法将其居中对齐 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

我试图将
ui视图
放在另一个视图的中心位置(就像弹出视图),但无论我做什么,我都无法将其居中对齐

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
}
我把背景颜色改成了黑色,这样我才知道它什么时候出现。
我不能用故事板来做这件事,因为它是在一个表视图上进行的,所以我尝试用编程的方式来做

您还需要从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:,宽度:,高度:)
上,点(x,y)是原点。在iOS中,这是左上角的点

关于:

在默认的核心图形坐标空间中,原点位于 在矩形的左下角,矩形延伸 朝向右上角。如果上下文有 翻转坐标空间通常在iOS上原点位于 左上角和矩形向右下角延伸 角落

所以要解决这个问题:

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)
另一种解决方案是在设置帧(特别是宽度/大小)后应用中心

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

自定义视图的用途是什么?在
CGRect(x:,y,width:,height:)
上,点(x,y)是原点,而不是中心。因此,要么从x中删除宽度/t,y中删除高度/2,要么随后更改中心设置其边框
customView.center=view.center
噢,太好了,谢谢!所以它总是-50,还是因为它应该是
宽度
高度
的一半?@TsGDev不总是-50,因为你的UIView是正方形的,它将是你的高度或宽度的一半。@TsGDev如果我的答案真的对你有帮助,那么你可以接受并投票决定答案,它将帮助其他开发者找到正确的答案。谢谢,绝对明星,谢谢!(我试着向上投票,但因为我有<15个代表,所以我不能):(@TsGDev你现在可以试试。接受答案需要15分钟。