UIButton vertical alignment doesn't work

二次信任 提交于 2019-12-12 10:47:44

问题


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;


回答1:


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;

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

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.

and

UIBaselineAdjustmentAlignBaselines

Adjust text relative to the position of its baseline.

Available in iOS 2.0 and later.

UIBaselineAdjustmentAlignCenters

Adjust text based relative to the center of its bounding box.

Available in iOS 2.0 and later.

UIBaselineAdjustmentNone

Adjust text relative to the top-left corner of the bounding box. This is the default adjustment.

Available in iOS 2.0 and later.

Note that the default adjustment for UILabel differs from that of a button's titleLabel.




回答2:


UIButton has a very nifty property named "titleEdgeInsets" which you can use (via UIEdgeInsetsMake to reposition the top and bottom margins of the title and get the thing centered, vertically.




回答3:


Have a look at Content-Alignment Vertical in storyboard




回答4:


I gave up trying to get this to work programmatically and just set a baseline constraint to another item. It seems to work great on IB (the content alignment property), even within a Stack View, but in code it does not work.



来源:https://stackoverflow.com/questions/18304450/uibutton-vertical-alignment-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!