0

如标题中所述,我想将 UILabel 中的文本水平和垂直居中..
如果我调用size to fit并水平对齐它,我可以垂直对齐它setAdjustsFontSizeToFitWidth 但同时使用两者似乎相互抵消..

绿色部分是 UILabel,红色部分是文字 ..

在此处输入图像描述

我想垂直对齐图像中的文本
谢谢!

4

1 回答 1

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

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

于 2013-07-29T13:05:59.317 回答