简体   繁体   English

将UIButton标题居中

[英]Center a UIButton title in its frame

I want to center (both x and y axis) this + sign within my UIButton CGRect but it keeps getting pushed down the y-axis. 我想在UIButton CGRect中将这个+符号居中(在x和y轴上居中),但是它一直被压向y轴。

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeSystem];
[aButton setTitle:@"+" forState:UIControlStateNormal];
[aButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:(40.0)]];
[aButton setBackgroundColor:[UIColor grayColor]];
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[aButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];

aButton.layer.cornerRadius = 25.0;

aButton.frame = CGRectMake(75.0, 100.0, 50.0, 50.0);

This would look more correct to you if you had ascenders and descenders. 如果您有上升和下降功能,这对您来说似乎更正确。 There's a label inside the button and it is sized to accommodate the height of the full range of possible characters of this font. 按钮内有一个标签,标签的大小可容纳此字体所有可能字符的高度。 If you don't like the position of the label, you're free to move it. 如果您不喜欢标签的位置,可以随意移动它。 There are a lot of ways to do this; 有很多方法可以做到这一点。 you might try playing with the button's titleEdgeInsets , for example. 例如,您可以尝试使用按钮的titleEdgeInsets进行播放。

设置标题和字体后添加以下行:

aButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 9, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM