简体   繁体   中英

How to center UIButton in Swift?

I have this code for my UIButton . What should I change in my CGRectMake to set my UIButton in the center of the screen for all screen sizes?

let loginBtn = UIButton(frame: CGRectMake(60, 360, 240, 40))
loginBtn.layer.borderColor = UIColor.whiteColor().CGColor
loginBtn.layer.borderWidth = 2
loginBtn.titleLabel!.font = UIFont.systemFontOfSize(24)
loginBtn.tintColor = UIColor.whiteColor()
loginBtn.setTitle("Login", forState: UIControlState.Normal)
self.view.addSubview(loginBtn)

For your place uibutton center of your view , update your cgrectmake as bleow..

CGRectMake((self.view.frame.size.width - 240) / 2, (self.view.frame.size.height - 40) / 2,240,40)  

or

You can add one line after your code

loginBtn.center = self.view.center

For SignUp Button :

signup.frame = loginBtn.bounds
signup.center = CGPointMake(loginBtn.center.x, loginBtn.center.y + loginBtn.frame.size.height + 10)

UIButtoncenter为其所在view的中心。

loginBtn.center = view.center

This will center the button across the whole screen, not just the view it's in:

let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.size.height / 2.0
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.size.width / 2.0

loginBtn.center = CGPoint(x: horizontalCenter, y: verticalCenter)

Edit:

As @LeoDabus pointed out, this can be compacted by using the midX and midY properties on CGRect :

let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.midY
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.midX

您需要在self.view.addSubview(loginBtn)之前添加以下行。

loginBtn.center = self.view.center

For Swift 4

@IBOutlet weak var btStart: UIButton!

on the middle of any screen (any device)

btStart.center = self.view.center

OR

btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y

on the center by x and 25 percent from top

btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y / 2

I found this to be the best solution for me..

Swift 4

myButton.center.x = self.view.frame.midX 
myButton.center.y = self.view.frame.midY

I found if I need to center things quite often, I usually use a generic solution.

extension UIViewController {
    func centerComponent(_ component: AnyObject) {
        let customView = component as! UIView
        customView.center.x = self.view.frame.midX
        customView.center.y = self.view.frame.midY
    }
}

then you can call it from any UIViewcontroller inside a function like so:

centerComponent(myButton)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM