2013-07-29 15 views
0

如標題所述,我希望將文本居中放在UILabel的水平和垂直方向上。
如果我打電話,我可以垂直對齊size to fit和水平對齊通過setAdjustsFontSizeToFitWidth 但同時使用起來似乎彼此抵消..在UILablel中設置文本,無論是垂直還是水平居中,無需更改框架

綠色的部分是的UILabel,紅色是文本..

enter image description here

我想垂直對齊圖像中看到的文字
謝謝!

+1

看到這個:http://stackoverflow.com/questions/1054558/vertically-align-text-within-a-uilabel?rq=1 –

+0

Did .. 它似乎可以解決問題 –

回答

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

它幫了我很多,希望它適合你。

相關問題