How can I make UIView
horizontally centered and 30px from the top of the view controller using CGRectMake
?
var draggableView: DraggableView = DraggableView(frame:CGRectMake(0 , 30, 260, 260))
draggableView.center = center
斯威夫特 3;
subView.center.x = view.center.x
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)
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
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
}
I am using the ' MMMaterialDesignSpinner ' library and creating a custom activity indicator in center of view. It's working correctly, you can change your custom view name like 'DraggableView'. I hope it's usable by you. This code is added into 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)
// in viewDidLoad or viewWillLayoutSubviews
draggableView.frame.origin.x = view.bounds.midX - draggableView.bounds.midX
This is a neat little extension for centering a 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
activityindicater is the view which you want to put in the center
self.activityindicater.center = self.baseView.center
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.