UIScreen.main,super.view和其他视图的中心不在屏幕中间

时间:2018-07-11 21:17:49

标签: ios swift uikit arkit cgrect

我的目标是在iPhone屏幕中央放置一个按钮,以使该按钮与屏幕边缘等距。我试图通过两种方式添加此按钮,方法是将框架的原点指定为父视图(super.view或UIScreen.main)的中心。我还尝试使用约束将按钮的中心重置为父视图的中心。在这两种情况下,按钮似乎都位于屏幕中心附近,而不是直接居中。需要注意的是,我正在使用ARSCNView,其次我没有使用.xib或情节提要来配置UI。您可以查看相机按钮的屏幕截图(红色): camera button not centered.

您可以在视图控制器中的以下位置查看我当前的代码:(我已经注释掉了定义屏幕中心的各种方式)

let sceneView = ARSCNView()

func addCameraButton(){
   //let cameraCenter = CGPoint(x:super.view.center.x, y: super.view.center.y)
   //let cameraCenter = CGPoint(x:UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
    let cameraCenter = CGPoint(x:sceneView.center.x, y:sceneView.center.y)
    let cameraSize = CGSize(width: 100, height: 100)
    let cameraRect = CGRect(origin: cameraCenter, size: cameraSize)
    cameraButton = KYShutterButton(frame:cameraRect, shutterType: .normal, buttonColor: UIColor.gray)
    cameraButton?.addTarget(self, action: #selector(cameraSnap), for: .touchUpInside)
    self.view.addSubview(cameraButton!)

    let verticalCenterCamera = NSLayoutConstraint(item: cameraButton, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0)

    let horizontalCenterCamera = NSLayoutConstraint(item: cameraButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0)

    NSLayoutConstraint.activate([verticalCenterCamera, horizontalCenterCamera])
    cameraButton?.layoutIfNeeded()

1 个答案:

答案 0 :(得分:0)

通过自动布局,以编程方式设置约束时,您需要将translateAutoresizingMaskIntoconstarints设置为false

cameraButton?.translateAutoresizingMaskIntoconstarints = false
let verticalCenterCamera = NSLayoutConstraint(item: cameraButton, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0)
let horizontalCenterCamera = NSLayoutConstraint(item: cameraButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activate([verticalCenterCamera, horizontalCenterCamera])
self.view.layoutIfNeeded()

//

采用框架布局

self.view.addSubview(cameraButton!)
self.cameraButton?.center = self.sceneView.center