My goal is to place a button at the center of an iPhone screen, so that the button is equally distant from the edges of the screen. I have attempted to add this button in two ways by assigning the frame an origin with the center of either the parent view, super.view or UIScreen.main. I have also tried using constraints to re-set the center of the button to the center of parent view. In both cases the button appears to be near the center of the screen but not directly centered. Things to note, I am using an ARSCNView and secondly I am not using .xib or storyboard to configure the UI. You can view a screen shot of the camera button(in red): camera button not centered.
You can look at what my current code looks like, in the view controller, here: (I have commented out the various ways of defining the center of the screen)
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()
With auto-layout you need to set translateAutoresizingMaskIntoconstarints
to false
when setting constraints programmatically
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()
//
With frame layout
self.view.addSubview(cameraButton!)
self.cameraButton?.center = self.sceneView.center