简体   繁体   中英

How to make the button centre aligned in all ios devices programmatically in swift 3?

I am creating an app where I have created a button programmatically , But I am having problem where this button does not show perfectly in the center when viewed in other devices such as iphone8, 7, and so on... It shows perfectly on a iphone X. How to show my button perfectly in all devices?

Here is my code:

let button = RideRequestButton()

let dropoffLocation = CLLocation(latitude: 37.6213129, longitude: -122.3789554)
let builder = RideParametersBuilder()
builder.dropoffLocation = dropoffLocation
builder.dropoffNickname = "Your Dropoff Location"
button.rideParameters = builder.build()

button.center = view.center
view.addSubview(button) 

You can use autolayout constraints to center the button.

    button.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(button)
    let centerXConstraint = NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
    let centerYConstraint = NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0)
    NSLayoutConstraint.activate([centerXConstraint, centerYConstraint])

Or you can set an autoresizing mask

    button.center = view.center
    button.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin]'

Or if you are targeting iOS 9 and above you can use NSLayoutAnchor

    button.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(button)
    button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

If you want to programmatically set a button at the center of your view then you can use center property or by set frame :

Using center property

    let button = RideRequestButton()
    button.backgroundColor = UIColor.gray
    button.frame.size.width = 200
    button.frame.size.height = 50
    button.center = self.view.center
    view.addSubview(button)

Using set frame by CGRect

    let button = RideRequestButton()
    button.backgroundColor = UIColor.gray
    button.frame.size.width = 200
    button.frame.size.height = 50
    button.frame = CGRect(x: self.view.frame.size.width/2 - button.frame.size.width/2, y: self.view.frame.size.height/2 - button.frame.size.height/2, width: button.frame.width, height: button.frame.height)
    view.addSubview(button)

Before this line

button.frame = CGRect(x:0,y:0,width:view.frame.width,height:50)
button.center = view.center

you have to give the button a frame

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