Ios UIL标签匹配问题
我使用此方法重新计算标签的框架:Ios UIL标签匹配问题,ios,uilabel,Ios,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;
- (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++;
}
}
如何使对象具有相对宽度并能正确重新计算?只需稍加修改代码,即可实现类似左对齐的效果:
- (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
方法是从
编辑:
您还可以在中找到许多处理字符串图形表示大小的有用方法。您可以尝试使用而不是
[label sizeToFit]代码>是相同的结果可能我在任何情况下都需要设置UIFont对不起,我有复制粘贴,但它不能正常工作:(我不需要分组或表格样式,我想要与第一张图片上相同的变体,但所有单词都包含在框架中。当然,很抱歉。我编辑了代码。这里有一台xp机器,所以我无法测试它。现在它应该可以工作了。谢谢,但我已经更正了您的代码,因为如果我们在下一次迭代中不增加if块中currentX的值ion我们得到相同的值,标签相互添加。我不知道问题是什么,但它不起作用,但如果我不使用[label sizeToFit],它就起作用;为什么:(不要使用sizeToFit
-这是UIView
的方法-它会更改其边界以适应所有子视图。它与将字符串适应UILabel
无关,因为字符(字符串)不被视为子视图。