Center Multi-Line Text on UIButton using IB

2020-06-06 17:53发布

How do you center text line-by-line in a UIButton using Interface Builder? I am scouring the options and just don't see it. Here's the button:

button with text not centered

7条回答
Summer. ? 凉城
2楼-- · 2020-06-06 18:18

Not all options are done using Interface Builder therefore you must do some of them by coding, and usually we do them inside the function viewDidLoad.

To center your text inside a button by code you can use the following:

button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

You can use the same technique to align the text to any direction, for example to the left:

button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

But this will take the text too much to the left and you might want to have some space before it keeping the alignment to the left, so you add an inset after the aligning code as follows:

button1.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

In this case we are pushing the text from the Y axis by 10 points. I say here points not pixels because as you know Apple uses the points technique to measure distances to be able to adapt easily between normal display and retina display (where retina is 2 times the normal one).

查看更多
登录 后发表回答