Placing UILabel in the center of screen

Osaama Shehzad picture Osaama Shehzad · Aug 14, 2016 · Viewed 9.2k times · Source

I have a UILabel which I want to be displayed at the center of screen regardless of which iPhone it is played on!

But I can't get it right! It's always somewhere else but not in the middle.

what am i doing wrong?

Here is the picture and code of what is happening!

so not in the middle!

class end: SKScene {

    var label = UILabel()


    override func didMoveToView(view: SKView) {
        scene?.backgroundColor = UIColor(red: CGFloat(59.0/255.0), green: CGFloat(89.0/255.0), blue: CGFloat(152.0/255.0), alpha: CGFloat(1.0))

        let w = UIScreen.mainScreen().bounds.width
        let h = UIScreen.mainScreen().bounds.height
        label = UILabel(frame: CGRect(x: w / 2, y: h / 2, width: 120, height: 30))
        label.text = "REPLAY"
        label.center = CGPoint(x: w / 2, y: 2)
        label.textColor = UIColor.whiteColor()
        self.view?.addSubview(label)

Answer

pbodsk picture pbodsk · Aug 14, 2016

I think your label actually is centered.

If I add a red background color like so:

label.backgroundColor = UIColor.redColor()

and change the vertical center to be the center of the screen, that is, changes this line in your example:

label.center = CGPoint(x: w / 2, y: 2)

to this:

label.center = CGPoint(x: w / 2, y: h / 2)

I end up with this:

centered label but not centered text

So, the label actually is centered. The text however, is not centered in the label, which makes it seems as if the text is not centered when you have no background color.

If I change the textAlignment to .Center and remove the background color again I end up with this result:

centered text in centered label

The final code example looks like this:

override func didMoveToView(view: SKView) {
    scene?.backgroundColor = UIColor(red: CGFloat(59.0/255.0), green: CGFloat(89.0/255.0), blue: CGFloat(152.0/255.0), alpha: CGFloat(1.0))

    let w = UIScreen.mainScreen().bounds.width
    let h = UIScreen.mainScreen().bounds.height

    label = UILabel(frame: CGRect(x: w / 2, y: h / 2, width: 120, height: 30))
    label.text = "REPLAY"
    label.center = CGPoint(x: w / 2, y: h / 2)
    label.textAlignment = .Center
    label.textColor = UIColor.whiteColor()
    self.view?.addSubview(label)
}

And when all that is said, then maybe you should look into the SKLabelNode as @whirlwind suggests in the comment, that way your label becomes an integrated part of the SKScene and not something that is bolted to the outer UIView (if that makes any sense to you).

Hope this helps you.