我试图在另一个视图(就像弹出式视图)中对齐一个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,所以我试图通过编程来实现它。结果图像
发布于 2018-07-03 10:37:36
您还需要从x和y中减去自定义视图高度和宽度的一半,如下所示:
let customView = CGRect(x: view.center.x - 50, y: view.center.y - 50, width: 100, height: 100)发布于 2018-07-03 10:38:19
你告诉它把左上角放在中间,所以你需要让它得到一半大小的位置。
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发布于 2018-07-03 10:52:21
在CGRect(x:, y:, width:, height:)上,点(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.centerhttps://stackoverflow.com/questions/51152390
复制相似问题