NSMutableArray *items
//包含15个项目
我需要在另一个标签上放一个我尝试这样但不起作用的标签
int count=20;
for(int i = 0; i < [items count]; i++){
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0,0,0,count)];
label.text = @"text"; //etc...
count+=20;
[_scroll addSubview:label];
}
我能做什么,谢谢
答案 0 :(得分:5)
您需要正确设置框架。
int count=20;
for(int i = 0; i < [items count]; i++){
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0,count,0,0)];
label.text = @"text"; //etc...
[label sizeToFit]; // resize the width and height to fit the text
count+=20;
[_scroll addSubview:label];
}
答案 1 :(得分:3)
正如rmaddy所建议的......添加一个新行来调整标签的高度,假设你有一个NSMutableArray对象'items'包含字符串。
float previousLabelHeight = 0.0;
for(int i = 0; i < [items count]; i++){
CGSize theSize = [[items objectAtIndex: i] sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(320, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap]; //can adjust width from 320 to whatever you want and system font as well
float newLabelHeight = previousLabelHeight + theSize.height;
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0,newLabelHeight,0,0)];
label.text = [items objectAtIndex: i];
[label sizeToFit]; // resize the width and height to fit the text
previousLabelHeight = newLabelHeight + 5 //adding 5 for padding
[_scroll addSubview:label];
}
干杯,
快乐编码。
答案 2 :(得分:0)
我认为您正在尝试更改帧的Y值,但CGRectMake()的最后一个参数是rect的高度。你想要第二个参数。
答案 3 :(得分:0)
以下是从数组中动态添加标签的Swift版本。
var previousLabelHeight: CGFloat = 0.0;
for dict in items {
let text: String = "Some text to display in the UILabel"
let size = heightNeededForText(text as NSString, withFont: UIFont.systemFontOfSize(15.0), width: scrollView.frame.size.width - 20, lineBreakMode: NSLineBreakMode.ByWordWrapping)
let newLabelHeight = previousLabelHeight + size;
let label = UILabel(frame: CGRectMake(0, newLabelHeight, 0, 0))
label.text = text
label.sizeToFit() // resize the width and height to fit the text
previousLabelHeight = newLabelHeight + 5 //adding 5 for padding
scroll.addSubview(label)
}
作为sizeWithFont:从ios 7.0弃用ConstraintedToSize, 我们必须使用NSString中的boundingRectWithSize方法....
func heightNeededForText(text: NSString, withFont font: UIFont, width: CGFloat, lineBreakMode:NSLineBreakMode) -> CGFloat {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
let size: CGSize = text.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle], context: nil).size//text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MA
return ceil(size.height);
}