2012-10-31 37 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在下一次迭代中,我们得到相同的值和标签相加。 –