2012-10-31 40 views
1

我用重新計算幀這個方法對我的標籤:的UILabel適應問題

- (void)fitElements {  
    CGFloat currentX = 0.0; 
    CGFloat currentY = 0.0;  
    for (UIView *view in elements) {  
     CGRect rect = view.frame; 
     rect.origin.x = currentX; 
     rect.origin.y = currentY;   
     currentX = rect.origin.x + rect.size.width + 5;   
     view.frame = rect;  
     if (currentX >= 420) { 
      currentX = 0.0; 
      currentY += rect.size.height + 5; 
     } 
    } 
} 

如果我的標籤跨越超過420我我的對象移動到下一行的邊界。

- (void)createElements { 
    NSInteger tag = 0; 
    for (NSString *str in words) { 
     UILabel *label = [[UILabel alloc] init]; 
     [self addGesture:label]; 
     [label setTextColor:[UIColor blueColor]]; 
     label.text = str; 
     [label setAlpha:0.8]; 
     [label sizeToFit]; 
     [elements addObject:label]; 
    } 
} 

這是它的外觀,如果我創建對象如上(使用[label sizeToFit];

enter image description here

我們可以看到我的所有的標籤出去邊境

,但如果我使用標籤與硬編碼框架我得到這個:

enter image description here

這是我想要的,但在這種情況下,我有靜態寬度的對象。

這是我用硬編碼框架的方法。

- (void)createElements { 
    NSInteger tag = 0; 
    for (NSString *str in words) { 
     UILabel *label = [[UILabel alloc] init]; 
     [self addGesture:label]; 
     [label setTextColor:[UIColor blueColor]]; 
     label.text = str; 
     [label setAlpha:0.8]; 
     [label setFrame:CGRectMake(0, 0, 100, 20)]; 
     [elements addObject:label]; 
     tag++; 
    } 
} 

如何使相對寬度的對象,它也可以正確重新計算?

+0

你可以嘗試使用[方法從這個答案](http://stackoverflow.com/a/3429732/653513)而不是'[label sizeToFit];' –

+0

是的相同的結果可能我需要在任何設置UIFont案例 –

回答

2

你可以實現的東西像你的代碼的小改左對齊:

- (void)fitElements { 
CGFloat currentX = 0.0; 
CGFloat currentY = 0.0; 
for (UILabel *view in elements) { //UIView changed to UILabel 
    CGRect rect = view.frame; 
    rect.origin.x = currentX; 
    rect.origin.y = currentY; 
    rect.size.width = [self widthOfString: view.text withFont:view.font]; 
    currentX = rect.origin.x + rect.size.width + 5; 
    view.frame = rect; 
    if (currentX + rect.size.width >= 420) { //EDIT done here 
     currentX = 0.0; 
     currentY += rect.size.height + 5; 
     rect.origin.x = currentX; 
     rect.origin.y = currentY; 
     view.frame = rect; 
     currentX = rect.origin.x + rect.size.width + 5; 
    } 
}} 

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font { 
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; 
    return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width; 
} 

widthOfString方法是從複製Stephen's answer

編輯:

您還可以找到很多在NSString UIKit Additions中處理字符串圖形表示大小的有用方法。

+0

對不起,我有複製粘貼,它不工作:(我不需要分組或表格樣式,我想與第一個圖像相同的變種,但所有的單詞包含在框架中 –

+0

當然,對不起,我編輯了代碼,在這裏有一臺xp機器,所以我無法測試它現在它應該工作 –

+1

謝謝,但我已更正您的代碼,因爲如果我們不增加currentX值if在下一次迭代中,我們得到相同的值和標籤相加。 –