thumbtackthief
thumbtackthief

Reputation: 6211

Programmatically set position of Swift element

I have a label defined in Storyboard and I'm trying to change its position based programatically. There are some existing questions on SO already that seem to address this issue, but none of the solutions seem to work (i.e., the label doesn't move). I've removed all existing constraints on the label to no avail. I've tried:

class LandingViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        titleLabel.frame = CGRectMake(100, 25, titleLabel.frame.size.width, titleLabel.frame.size.height)
        }

I also tried

titleLabel.center = CGPointMake(120, 150)

instead of titleLabel.frame

Am I missing something?

Upvotes: 4

Views: 11980

Answers (2)

LuAndre
LuAndre

Reputation: 1133

Do you want to center the label according the screen size? if so, try the below (Note the UIlabel is created programmatically)

 var tempLabel:UILabel
 override func viewDidLoad() {
      super.viewDidLoad()

     //gets screen frame size
     var fm: CGRect = UIScreen.mainScreen().bounds

     //creates a temp UILabel
     tempLabel = UILabel(frame:  CGRectMake(0, fm.frame.size.height, fm.size.width, fm.size.height))

     //aligns the UIlabel to center
     tempLabel.textAlignment = NSTextAlignment.Center

    //adding UIlabel to view
    view.addSubview(tempLabel)
}

Upvotes: 1

Stuart
Stuart

Reputation: 37053

When using AutoLayout, views instantiated in storyboards with constraints have their translatesAutoresizingMaskIntoConstraints property set to false, in contrast to views instantiated programmatically. This is because interface builder expects constraints to fully specify the layout of that view.

To modify your frame/bounds/center manually, set this property to true in code. This will make the view's layout behave in a way similar to how things worked in the days before AutoLayout, so be aware that any constraints you specify on the view may conflict or behave unexpectedly if you just specify this property when you actually want it to be laid out using constraints.

I would suggest that you first consider whether what you actually want to do is specify your label's position through AutoLayout constraints. These days, it is rare that you actually want to specify a position manually, as you have done above.

Upvotes: 5

Related Questions