Rizon
Rizon

Reputation: 1546

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;

enter image description here

Upvotes: 6

Views: 8855

Answers (4)

Marc Etcheverry
Marc Etcheverry

Reputation: 1089

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.

Upvotes: 0

Suraj K Thomas
Suraj K Thomas

Reputation: 5883

enter image description here

Have a look at Content-Alignment Vertical in storyboard

Upvotes: 0

emb
emb

Reputation: 405

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.

Upvotes: 3

Michael Dautermann
Michael Dautermann

Reputation: 89509

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.

Upvotes: 5

Related Questions