NSLocalization + Storyboard using Swift

130 views Asked by At

So this is very strange:

I created a small UIView in Storyboard, changed its color so we can see it. I also created a button so I can make this view bigger.

What happens is it only works if I don't access NSLocalizedString. If I decomment the line it stops working.

Why is this?

class MasterViewController: UIViewController {

    @IBOutlet weak var bar: UIView!
    @IBOutlet weak var button: UIButton!

    var integer : Int = 0

    @IBAction func makeBarGrow(sender : AnyObject) {
        self.integer++
       //self.button.setTitle(NSLocalizedString("test \(integer)", comment : "test"), forState:UIControlState.Normal)
        self.bar.frame = CGRectMake(self.bar.frame.origin.x,
            self.bar.frame.origin.y,
            self.bar.frame.size.width + 10,
            self.bar.frame.size.height)
    }
}

Thank you

1

There are 1 answers

1
vacawama On BEST ANSWER

When you set the label on your button, Auto Layout runs and sets the frame of your bar back to its initial value. When Auto Layout is enabled, you shouldn't adjust frame sizes. Instead, you should use size constraints like so:

  1. Add an Auto Layout constraint on your bar that sets its width. To do this, select your bar view in Interface Builder and click the Auto Layout Pin icon |-[]-|, click the box next to Width, and set the constant to your desired initial value. Then click Add 1 Constraint at the bottom.

  2. Add an IBOutlet to this constraint in your ViewController by Control dragging from the constraint in the Document Layout View to your code:

    @IBOutlet weak var barWidth: NSLayoutConstraint!
    
  3. In makeBarGrow, replace frame adjusting code with:

    barWidth.constant += 10