1

我有一个包含 Person 类型对象的 NSMutableArray。Person 对象包含 NSString *name、NSString *dateStamp 和 NSString *testScore 的参数。我想使用快速枚举做的是将每个对象的参数显示为视图中的一行上的 UILabel,每个对象都显示在每一行上。

问题是 NSMutableArray 可能包含任意数量的对象,因此视图上可能有一两行标签,或者视图上有几行。我想创建一个 for 循环,该循环将动态填充视图中的每个对象在一行上(并且始终保持间距),并允许用户向下滚动以查看任何更向下且最初无法在屏幕上看到的行.

我的 for 循环如下所示:

for (Person *checkPerson in personList) {
    UILabel *label1 =  [[UILabel alloc] initWithFrame: CGRectMake(10, 10, 50, 20)];
    label1.text = Person.name;

    UILabel *label2 =  [[UILabel alloc] initWithFrame: CGRectMake(70, 10, 50, 20)];
    label2.text = Person.dateStamp;

    UILabel *label3 =  [[UILabel alloc] initWithFrame: CGRectMake(130, 10, 50, 20)];
    label3.text = Person.testScore;

    [self.view addSubView:label1];
    [self.view addSubView:label2]; 
    [self.view addSubView:label3];
 }

我需要做的是动态调整 CGRectMake 字段中的“y”值,以便每个对象在 NSMutableArray 迭代时依次向下移动到另一行,这样用户可以向下滚动以进一步查看其他行,如果必要的。滚动功能是自动添加的吗?

4

2 回答 2

2

你应该做块枚举,因为这也给你一个索引,你可以用它来计算y

[personList enumerateObjectsUsingBlock:^(Person *person, NSUInteger idx, BOOL *stop) {
    UILabel *label1 =  [[UILabel alloc] initWithFrame: CGRectMake(10, 10+20*idx , 50, 20)];
    label1.text = person.name;
    UILabel *label2 =  [[UILabel alloc] initWithFrame: CGRectMake(70, 10+20 *idx, 50, 20)];
    label2.text = person.dateStamp;

    UILabel *label3 =  [[UILabel alloc] initWithFrame: CGRectMake(130, 10+20*idx, 50, 20)];
    label3.text = person.testScore;

    [self.view addSubView:label1];
    [self.view addSubView:label2]; 
    [self.view addSubView:label3];
}];

您应该将它们放在 UIScrollView 上,根据数组中元素的数量在其中设置 contentSize。

scrollView.contentSize = CGSizeMake(<width>, [personList count] / 3 *30);

您还应该考虑使用 UITableView。这可能更容易,并且单元重用可以保持较低的内存使用率。

于 2012-12-17T20:16:18.020 回答
0

只需在您的代码中添加一个y变量并在每次迭代后增加它

CGFloat y = 10;
for (Person *checkPerson in personList) {
    UILabel *label1 =  [[UILabel alloc] initWithFrame: CGRectMake(10, y, 50, 20)];
    label1.text = Person.name;

    UILabel *label2 =  [[UILabel alloc] initWithFrame: CGRectMake(70, y, 50, 20)];
    label2.text = Person.dateStamp;

    UILabel *label3 =  [[UILabel alloc] initWithFrame: CGRectMake(130, y, 50, 20)];
    label3.text = Person.testScore;

    [self.view addSubView:label1];
    [self.view addSubView:label2]; 
    [self.view addSubView:label3];

    y+=80;
 }

但正如其他人所说,一个 UITableView 注定要完成这样的任务:D

于 2012-12-17T20:34:33.153 回答