Emm
Emm

Reputation: 1603

How to put buttons on center with swift code using Xcode 7 Beta?

I made a game with Xcode 7 Beta, I put some buttons but they don't arrange as it's supposed, On some iPhones they stay on the left on some other iPhones they stay on the right, and It's supposed to stay on center.

This is on iPhone 5/5s and how is supposed to beenter image description here

This is on iPhone 4senter image description here

This is on iPhone 6 enter image description here

And the code that I used is:

override func didMoveToView(view: SKView) {

    leaderboard()
    facebookShare()
    twitterShare()
    removeAds()
}




func leaderboard() {
   let myNode = SKSpriteNode(imageNamed: "buttonLeaderboard")

    myNode.position = CGPoint(x: CGFloat(120 + BUTTON_WIDTH + BUTTON_SPACING), y: view!.frame.maxY * 0.25)
    myNode.size = CGSizeMake(80.0, 40.0)
    self.addChild(myNode)
}


func facebookShare() {
    let facebookShareNode = SKSpriteNode(imageNamed: "buttonFacebookShare")
    facebookShareNode.position = CGPoint(x: CGFloat(130 + BUTTON_WIDTH * 2 + BUTTON_SPACING * 2), y: view!.frame.maxY * 0.25)
    facebookShareNode.size = CGSizeMake(40.0, 40.0)
    self.addChild(facebookShareNode)
}


func twitterShare() {
    let twitterShareNode = SKSpriteNode(imageNamed: "buttonTwitterShare")
    twitterShareNode.position = CGPoint(x: CGFloat(180 + BUTTON_WIDTH * 2 + BUTTON_SPACING * 2), y: view!.frame.maxY * 0.25)
    twitterShareNode.size = CGSizeMake(40.0, 40.0)
    self.addChild(twitterShareNode)
}

func removeAds() {
    let removeAdsNode = SKSpriteNode(imageNamed: "buttonRemoveAds")
    removeAdsNode.position = CGPoint(x: CGFloat(250 + BUTTON_WIDTH * 2 + BUTTON_SPACING * 2), y: view!.frame.maxY * 0.25)
    removeAdsNode.size = CGSizeMake(80.0, 40.0)
    self.addChild(removeAdsNode)
}

I hope You can help me what I missed.

Upvotes: 0

Views: 794

Answers (1)

Lachezar
Lachezar

Reputation: 6703

You might want to use Autolayout's constraints mechanism to define the desired location of these buttons on different screens. Otherwise you might end up in unneeded and complicated calculations of widths and offsets just to position few elements in the view.

You can group those buttons in a UIView element and center the element using constraints.

Example of setting central horizontal and vertical constraints of an element: center constraints

Upvotes: 1

Related Questions