将UILablel中的Text设置为垂直和水平居中而不更改框架

时间:2013-07-29 12:28:09

标签: ios ipad cocoa uilabel

正如标题中所述,我想将文本在UILabel中水平和垂直居中。
如果我拨打size to fit并通过setAdjustsFontSizeToFitWidth水平对齐,我可以垂直对齐它 但是将两者结合使用似乎相互抵消..

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

enter image description here

我想垂直对齐文字,如图所示 谢谢!

1 个答案:

答案 0 :(得分: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;
}

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