How can I horizontally center a UIView?
You cannot center a view in a view controller, because a view controller is not a view and doesn't have a coordinate system.
You can center a view relative to another view. Presumably you want to center draggableView
relative to the view controller's view. Assuming self
is the view controller, and draggableView
will be a direct subview of the view controller's view:
var draggableView: DraggableView = DraggableView(frame:CGRectMake(0 , 30, 260, 260))
self.view.addSubview(draggableView)
draggableView.center = self.view.center
Try:
let size = 260
let screenWidth = self.view.frame.size.width
let frame = CGRectMake((screenWidth / 2) - (size / 2), 30, size, size)
let draggableView = DraggableView(frame: frame)
self.view.addSubview(draggableView)
Although Rob Mayoff is correct, it might be worthwhile to consider centering your frame in viewWillLayoutSubviews, which is called upon device rotation. You can also use the properties center.x and center.y of center to align based on axis. No need to call self in this instance.
override func viewWillLayoutSubviews() {
draggableView.center = view.center
}
Swift 3;
subView.center.x = view.center.x