首页 文章

UILabel垂直居中,自动收缩

提问于
浏览
44

这与其他所有“我如何将文本置于 UILabel 中的中心”有点不同......

我有一个带有一些文本的 UILabel ,我希望将文本垂直居中于 UILabel . 什么's the big deal, right? That'是默认值 . 问题来了,因为我的文字是动态的,我打开了自动收缩 . 随着文本变大,字体大小缩小 . 你得到这种行为 .

enter image description here

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

容易,对吗?我只记得框架的原始中心 viewDidLoad

self.workoutTimeCenter = _workoutTimeLabel.center;

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

[_workoutTimeLabel sizeToFit];
    _workoutTimeLabel.center = _workoutTimeCenter;

好吧, sizeToFit 确实,我想,它确实应该做什么,调整框架的大小,使文字适合而不缩小!

enter image description here

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

5 回答

  • 2

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

    来自docs

    baselineAdjustment控制文本需要缩小以适应标签时如何调整文本基线 . @property(非原子)UIBaselineAdjustment baselineAdjustment
    讨论如果adjustsFontSizeToFitWidth属性设置为YES,则此属性控制在需要调整字体大小的情况下文本基线的行为 . 此属性的默认值为UIBaselineAdjustmentAlignBaselines . 仅当numberOfLines属性设置为1时,此属性才有效 .

    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
    
  • 1
    -(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 here

    enter 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

  • -4

    在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)

  • 92

    尝试实现此逻辑:

    -(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;
    }
    

    它给了我很多帮助 . 希望它适合你 .

  • 2

    尝试

    yourLabel.textAlignment = UITextAlignmentCenter;
    

相关问题