ios 使用自动收缩在 UILabel 中垂直居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17972036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:34:15  来源:igfitidea点击:

Center vertically in UILabel with autoshrink

iosuilabel

提问by Paul Cezanne

This is a little different from all the other "How do I center the text in a UILabel" questions here...

这与UILabel此处的所有其他“我如何将文本居中”问题略有不同......

I have a UILabelwith some text in it, I want to center the text vertically in the UILabel. What's the big deal, right? That's the default. The problem comes because my text is dynamic and I have autoshrink turn on. As the text grows larger, the font size shrinks. You get this behavior.

我有UILabel一些文本,我想将文本垂直居中在UILabel. 有什么大不了的,对吧?这是默认设置。问题出现是因为我的文本是动态的,而且我打开了自动收缩。随着文本变大,字体大小会缩小。你会得到这种行为。

enter image description here

在此处输入图片说明

Notice that the font baseline has not moved, I want it to move so the numbers are centered vertically in the UILabel'sframe.

请注意,字体基线没有移动,我希望它移动以便数字在UILabel's框架中垂直居中。

Easy, right? I just remember the frame's original center in viewDidLoad

很简单,对吧?我只记得框架的原始中心viewDidLoad

    self.workoutTimeCenter = _workoutTimeLabel.center;

and then I call sizeToFitafter I change the the text, right?

然后我sizeToFit在更改文本后调用,对吗?

    [_workoutTimeLabel sizeToFit];
    _workoutTimeLabel.center = _workoutTimeCenter;

Well, sizeToFitdid, I guess, exactly what it was supposed to do, resize the frame so the text fits without shrinking!

好吧,sizeToFit我想,正是它应该做的,调整框架的大小,使文本适合而不收缩!

enter image description here

在此处输入图片说明

How can I vertically center the text in a UILabelwhile respecting baselines and autoshrink? (Note, an iOS5and later solution is fine and I can even deal with an iOS6and later solution.)

如何UILabel在尊重基线和自动收缩的同时垂直居中文本?(请注意,iOS5及更高版本的解决方案很好,我什至可以处理iOS6及更高版本的解决方案。)

回答by TomSwift

In my experience you can just set the -[UILabel baselineAdjustment]property to UIBaselineAdjustmentAlignCentersto achieve the effect you're describing.

根据我的经验,您只需将-[UILabel baselineAdjustment]属性设置为UIBaselineAdjustmentAlignCenters即可实现您所描述的效果。

From the docs:

文档

baselineAdjustment

Controls how text baselines are adjusted when text needs to shrink to fit in the label.

@property(nonatomic) UIBaselineAdjustment baselineAdjustment

Discussion

If the adjustsFontSizeToFitWidthproperty 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 numberOfLinesproperty is set to 1.

基线调整

控制文本需要缩小以适应标签时如何调整文本基线。

@property(nonatomic) UIBaselineAdjustment baselineAdjustment

讨论

如果该adjustsFontSizeToFitWidth属性设置为YES,则在需要调整字体大小的情况下,此属性控制文本基线的行为。此属性的默认值为UIBaselineAdjustmentAlignBaselines。此属性仅在numberOfLines设置为 时有效1

and

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

UIBaselineAdjustmentAlignCenters
相对于其边界框的中心调整文本。

EDIT: adding a full view-controller that demonstrates this:

编辑:添加一个完整的视图控制器来演示这一点:

@interface TSViewController : UIViewController
@end

@implementation TSViewController

- (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla
{
    UILabel* label = [[UILabel alloc] initWithFrame: f];
    label.baselineAdjustment = bla;
    label.adjustsFontSizeToFitWidth = YES;
    label.font = [UIFont fontWithName: @"Courier" size: 200];
    label.text = @"00";
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor lightGrayColor];
    label.userInteractionEnabled = YES;
    [self.view addSubview: label];

    UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)];
    centerline.backgroundColor = [UIColor redColor];
    [self.view addSubview: centerline];

    UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)];
    [label addGestureRecognizer: tgr];
}

- (void) viewDidLoad
{
    [super viewDidLoad];

    [self addLabelWithFrame: CGRectMake(0, 0, 320, 200)
         baselineAdjustment: UIBaselineAdjustmentAlignCenters];

    [self addLabelWithFrame: CGRectMake(0, 220, 320, 200)
         baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
}

- (void) onTap: (UITapGestureRecognizer*) tgr
{
    UILabel* label = (UILabel*)tgr.view;
    NSString* t = [label.text stringByAppendingString: @":00"];
    label.text = t;
}

@end

回答by Peter Lapisu

when working in IB, be sure to set align baselines to center

在 IB 中工作时,请确保将基线对齐设置为居中

enter image description here

在此处输入图片说明

Note: line break CANNOT be word wrap for this to work, so it will NOT work multiline (good to set the line break to Truncate tail)

注意:换行符不能是自动换行,因此它不会工作多行(最好将换行符设置为截断尾部)

回答by TheTiger

-(void)fitVerticallyToLabel:(UILabel *)lbl
{
    CGFloat fontSize = lbl.frame.size.width / lbl.text.length;
    [lbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:fontSize]];

    CGRect rect = lbl.frame;
    rect.origin.y += rect.size.height - fontSize;
    rect.size.height = fontSize;
    [lbl setFrame:rect];
}

How to Use: Call this method after setting the text to your label.

如何使用:将文本设置为标签后调用此方法。

    label.text = @"text";
    [self fitVerticallyToLabel:label];

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

Note: I ahev taken UILabel from xib. You can take it programmatically too in that case you will have to set its text alignment NSTextAlignMentCenter

注意:我从 xib 中获取了 UILabel。您也可以以编程方式使用它,在这种情况下,您必须设置其文本对齐方式 NSTextAlignMentCenter

回答by Aniket Kote

Try to implement this logic:

尝试实现这个逻辑:

-(void)adjustLabel1Text1:(NSString *)text1 
{
    UILabel *lbl_first = [UIFont fontWithName:@"Helvetica" size:12];



    text1 = [text1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


    float hedingLblHeight = [self calculateHeightOfTextFromWidth:text1 : [UIFont fontWithName:@"Helvetica" size:12] :118 :UILineBreakModeWordWrap];

    lbl_first.text=text1;


    [lbl_first setFrame:CGRectMake(lbl_first.frame.origin.x, lbl_first.frame.origin.y, 118, hedingLblHeight)];
    lbl_first.lineBreakMode = UILineBreakModeWordWrap;
    lbl_first.numberOfLines = 0;
    [lbl_first sizeToFit];




//////////Adjust the lable or any UIControl below this label accordingly.

    float endResultHeight=[self calculateHeightOfTextFromWidth:text2 : [UIFont fontWithName:@"Helvetica" size:15] :299 :UILineBreakModeWordWrap];

    if(hedingLblHeight>secondImgTitleHeight)
    {
    [lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
    }
    else
    {
        [lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];

    }

    lbl_endResult.lineBreakMode=UILineBreakModeWordWrap;
    lbl_endResult.numberOfLines = 0;
    [lbl_endResult sizeToFit];



}

-(float) calculateHeightOfTextFromWidth:(NSString*)text : (UIFont*) withFont:(float)width :(UILineBreakMode)lineBreakMode
{

    CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];

    return suggestedSize.height;
}

It has helped me a lot.Hope it works for you.

它对我帮助很大。希望它对你有用。

回答by Nasir

Try

尝试

yourLabel.textAlignment = UITextAlignmentCenter;