OGeek|极客世界-中国程序员成长平台

标题: ios - 从 UIView 内的 NSMutableArray 垂直显示 UILabel [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:28
标题: ios - 从 UIView 内的 NSMutableArray 垂直显示 UILabel

我有一个数组对象列表,我将其传递给循环并将其动态显示为 UILabel。但是我需要这些值以垂直显示它。以下是我的代码,

 labelArrays = [NSMutableArray arrayWithObjects"One”, @“Two”, @“Three",@"four",@"five",@"six" ,nil];

//inside a method with a loop am passing the array and creating the labels.
-(void) createlabelCGRect) frame{
  float xCoordinate = frame.origin.x;
  float yCoordinate = frame.origin.y;
  int labelHeight =30;
  int gapBetweenTwoLabels =2;
  int labelWidth = 100;
  for(int counter = 0; counter < [labelArrays count]; counter++){
  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(xCoordinate,yCoordinate,labelWidth,labelHeight)];
  label.text = [labelArrays objectAtIndex:counter];
  [self addSubview:label];
  xCoordinate = xCoordinate + labelWidth + gapBetweenTwoLabels;
 }
}
//frame
[self createlabel:CGRectMake(25,130,100,40)];

这显示我为

one two three four five six

但我需要它

one two three
four five six

谁能建议我如何实现它?注意:我在 UIView 中使用此方法,而不是在 Controller 中。



Best Answer-推荐答案


按照@Larme 所述更改您的 y 坐标

labelArrays = [NSMutableArray arrayWithObjects"One”, @“Two”, @“Three", @"four", @"five", @"six" ,nil];

如果你想输出如下

one
two
three
four
five
six

-(void) createlabelCGRect) frame {
    CGFloat xCoordinate = frame.origin.x;
    CGFloat yCoordinate = frame.origin.y;
    CGFloat labelHeight = frame.size.height;
    CGFloat labelWidth = frame.size.width;
    CGFloat gapBetweenTwoLabels = 2;

    for(int counter = 0; counter < [labelArrays count]; counter++) {
        UILabel *label = [[UILabel alloc]initWithFrame : CGRectMake(xCoordinate, yCoordinate, labelWidth, labelHeight)];
        label.text = [labelArrays objectAtIndex:counter];
        [self addSubview:label];
        yCoordinate = yCoordinate + labelHeight + gapBetweenTwoLabels;
    }
}

但如果你想输出为:

one two three
four five six

-(void) createlabelCGRect) frame {
    CGFloat xCoordinate = frame.origin.x;
    CGFloat yCoordinate = frame.origin.y;
    CGFloat labelHeight = frame.size.height;
    CGFloat labelWidth = frame.size.width;
    CGFloat gapBetweenTwoLabels = 2;

    for(int counter = 0; counter < [labelArrays count]; counter++) {
        UILabel *label = [[UILabel alloc]initWithFrame : CGRectMake(xCoordinate, yCoordinate, labelWidth, labelHeight)];
        label.text = [labelArrays objectAtIndex:counter];
        [self addSubview:label];
        if((counter+1)%3 == 0) {
            xCoordinate = 0;
            yCoordinate = yCoordinate + labelHeight + gapBetweenTwoLabels;
        } else {
            xCoordinate = xCoordinate + labelWidth + gapBetweenTwoLabels;
        }
    }
}

函数调用

[self createlabel:CGRectMake(25,130,100,40)];

关于ios - 从 UIView 内的 NSMutableArray 垂直显示 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706578/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4