我使用此方法重新计算标签的框架:
- (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++;
}
}
如何制作具有相对宽度的对象,并且还可以正确重新计算?
答案 0 :(得分: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中找到许多处理字符串图形表示大小的有用方法。