Search code examples
macoscocoaxcode6autolayoutnsbutton

Button with varying localized title with auto layout


I am looking into taking the plunge and use Auto Layout on an existing app. The interface has a button on the main window. The button changes its title depending on the state of the app. I plan to localize the app.

Since Auto Layout does not know (in the NIB) the length of the various titles that the button will adopt, how can I guarantee that the button will, for each localization, be sized in such a way that it will fit the longest-length title in each localization?

What is the right way to accomplish this? Many thanks.


Solution

  • You don't need to change much. You just add the alignment constraints whatever you added. Now give it width and height constraints and make them greater than equals to the minimum value you wanted. See this.

    enter image description here

    I have added center horizontal and vertical for alignment. This you can change to any. Now the width is here greater than equals to 42.0 and the height is greater than equals to 21.0 . Now if you just change the text of the button then it will increase its height and width according to that. You just need to call this line just after changing the text.

    [self.view layoutIfNeeded];
    

    Now you may have question that you want to limit the width and then increase height. Here is the solution. You give it width less than equals to max width and it will not increase the width more than that. See here.

    enter image description here

    Here my max width is 200.0. But make sure that if you are adding those layout constraints in iOS and it is a UILabel then than Lines is 0 and if it is a UIButton then the Line Break is Word Wrap or Character Wrap, but in OS X increasing height of NSButton depends on your button type.