1

我使用这种方法为我的标签重新计算框架:

- (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];

在此处输入图像描述

我们可以看到我所有的标签都超出了边界

但是如果我使用带有硬编码框架的标签,我会得到这个:

在此处输入图像描述

这就是我想要的,但在这种情况下,我有对象的静态宽度。

这是我使用硬编码框架的方法。

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

如何制作具有相对宽度的对象并且它也可以正确重新计算?

4

1 回答 1

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方法是从斯蒂芬的答案中复制的

编辑:

您还可以在NSString UIKit Additions中找到许多处理字符串图形表示大小的有用方法。

于 2012-10-31T15:07:41.827 回答