2

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

    }

我能做什么谢谢

4

4 回答 4

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];
}
于 2013-09-10T00:12:42.800 回答
3

正如 rmaddy 所建议的...添加一个新行来调整标签的高度,假设您有一个包含字符串的 NSMutableArray 对象“项目”。

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

干杯,

快乐编码。

于 2013-09-10T11:15:09.407 回答
0

我认为您正在尝试更改框架的 Y 值,但 CGRectMake() 的最后一个参数是矩形的高度。你想要第二个参数。

于 2013-09-10T00:05:33.577 回答
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: ConstraintedToSize 已从 ios 7.0 中弃用,我们必须使用 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);
}
于 2016-05-21T07:34:04.530 回答