UIButton 垂直对齐不起作用 [英] UIButton vertical alignment doesn't work
问题描述
我不明白为什么在下面的代码中,标题对齐不是保持在顶部.
I can't figure why in the following code, the title alignment isn't remain Top.
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn2.titleLabel.font = [UIFont systemFontOfSize:53];
btn2.frame = CGRectMake(20, 20, 270, 44);
[btn2 setTitle:@"test1 test2 test3 test4 test5 test6 test7" forState:UIControlStateNormal];
[btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn2.titleLabel.minimumFontSize = 1.0;
btn2.titleLabel.adjustsFontSizeToFitWidth = YES;
btn2.titleLabel.numberOfLines = 1;
btn2.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
推荐答案
这种行为是由于按钮的 titleLabel
的 baselineAdjustment
默认属性造成的.如果你将它设置为 UIBaselineAdjustmentNone
,你应该会得到你想要的效果.
This behavior is due to the baselineAdjustment
default property of the button's titleLabel
. If you set this to UIBaselineAdjustmentNone
, you should get the effect you're looking for.
btn2.titleLabel.baselineAdjustment = UIBaselineAdjustmentNone;
来自 UILabel 的 rel="nofollow">docs:
From the docs for UILabel
:
控制文本基线的调整方式需要缩小以适应标签.
baselineAdjustment
Controls how text baselines are adjusted when text needs to shrink to fit in the label.
@property(nonatomic) UIBaselineAdjustment baselineAdjustment
讨论
如果 adjustsFontSizeToFitWidth
属性设置为 YES
,则此属性控制需要调整字体大小时文本基线的行为.此属性的默认值为 UIBaselineAdjustmentAlignBaselines
.此属性仅在 numberOfLines
属性设置为 1
时有效.
Discussion
If the adjustsFontSizeToFitWidth
property is set to YES
, this property controls the behavior of the text baselines in situations where adjustment of the font size is required. The default value of this property is UIBaselineAdjustmentAlignBaselines
. This property is effective only when the numberOfLines
property is set to 1
.
和
相对于其基线位置调整文本.
UIBaselineAdjustmentAlignBaselines
Adjust text relative to the position of its baseline.
适用于 iOS 2.0 及更高版本.
Available in iOS 2.0 and later.
相对于其边界框的中心调整文本.
Adjust text based relative to the center of its bounding box.
适用于 iOS 2.0 及更高版本.
Available in iOS 2.0 and later.
相对于边界框的左上角调整文本.这是默认调整.
Adjust text relative to the top-left corner of the bounding box. This is the default adjustment.
适用于 iOS 2.0 及更高版本.
Available in iOS 2.0 and later.
请注意,UILabel
的默认调整与按钮的 titleLabel
的默认调整不同.
Note that the default adjustment for UILabel
differs from that of a button's titleLabel
.
这篇关于UIButton 垂直对齐不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!