How can I horizontally center a UIView?

How can I make a UIView horizontally and 30px from the top of the view controller using CGRectMake ?

 var draggableView: DraggableView = DraggableView(frame:CGRectMake(0 , 30, 260, 260)) draggableView.center = center 
+8
ios swift
source share
8 answers

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) 
+15
source share

Swift 3;

 subView.center.x = view.center.x 
+14
source share

You cannot center the view in the view controller because the view controller is not a view and does not have a coordinate system.

You can center the view relative to another view. Presumably you want to center the draggableView relative to the view controller view. Assuming self is a view controller, and draggableView will be a direct subview of a view controller view:

 var draggableView: DraggableView = DraggableView(frame:CGRectMake(0 , 30, 260, 260)) self.view.addSubview(draggableView) draggableView.center = self.view.center 
+10
source share

Although Rob Mayoff is right, it might be worth considering centering your frame in viewWillLayoutSubviews, which is called device birth. You can also use the center.x and center.y properties of the center to align along the axis. There is no need to call yourself in this case.

 override func viewWillLayoutSubviews() { draggableView.center = view.center } 
+3
source share

I use the MMMaterialDesignSpinner library and create a custom activity indicator in the center of the review. It works correctly, you can change your own view name, for example "DraggableView". Hope this helps you. This code is added to the viewDidLoad function in swift 3.

 var loader = MMMaterialDesignSpinner() let size:CGFloat = 40.0 let screenWidth = self.view.frame.size.width let screenHeight = self.view.frame.size.height loader = MMMaterialDesignSpinner(frame: CGRect(x: (screenWidth / 2) - (size / 2), y: (screenHeight / 2) - (size / 2), width: size, height: size)) loader.tintColor = UIColor.blue loader.lineWidth = 4.0 loader.lineCap = kCALineCapRound; view.addSubview(loader) 
+1
source share

This is a neat little extension to center the view or object:

 extension CGPoint { static var Center: CGPoint { return CGPoint(x: UIScreen.main.bounds.maxX/2, y: UIScreen.main.bounds.maxY/2) } } 

And then use it like this:

 textField.center = CGPoint.Center 
0
source share

activityindicater is the view you want to center

self.activityindicater.center = self.baseView.center

0
source share

Swift 3:

 // in view controller, in viewDidLoad function let draggableView = DraggableView(frame: CGRect(x: 0, y: 30, width: 260, height: 260)) draggableView.frame.origin.x = view.bounds.midX - draggableView.bounds.midX 
0
source share

All Articles