Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center UILabel in Swift?

I'm trying to center some text but I it doesn't seem to be working.

import UIKit  class ViewController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view, typically from a nib.           let title = UILabel()         title.text = "Some Sentence"         title.numberOfLines = 0         title.frame = CGRectMake(self.view.bounds.size.width/2,50,self.view.bounds.size.width, self.view.bounds.size.height) // x , y, width , height         title.textAlignment = .Center         title.sizeToFit()         title.backgroundColor = UIColor.redColor()         self.view.addSubview(title)      }      override func didReceiveMemoryWarning() {         super.didReceiveMemoryWarning()         // Dispose of any resources that can be recreated.     }  } 

That is the code that I'm using but this is what I get:

enter image description here

It's not center to the screen. Can someone tell me what am I doing wrong?

like image 632
elpita Avatar asked Jan 07 '16 01:01

elpita


People also ask

How do you center a label in view?

Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content. This is the best answer, having the label frame is centered is not enough for centering the text, very useful if your labels are localized!

How do I center a label in Xcode?

click on Align button on bottom toolbar in IB then select Horizontal or Vertical center. First you might want to fix width and height as well, if you want to preserve size.

What is UILabel in Swift?

A view that displays one or more lines of informational text.


1 Answers

To center a UILabel just add this row

x and y:

title.center = self.view.center 

x:

title.center.x = self.view.center.x 

y:

title.center.y = self.view.center.y 
like image 97
Rashwan L Avatar answered Sep 20 '22 09:09

Rashwan L