如何将字符串数组插入UILabel
,并让它们加载或按1计数?我正在尝试将以下数组加载到UILabel
:
self.array = [NSArray arrayWithObjects:@"Testing 1",@"Testing 2",@"Testing 3", nil];
这里我使用的是一个UIScrollView,它可以从每张幻灯片自动更改为每张幻灯片:
for (int i=1; i<=3; i++) {
// create label
UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,30)];
text.text = [NSString stringWithFormat:@"%@", self.array];
text.font=[UIFont fontWithName:@"HelveticaNeueLTStd-LtCn" size:15];
text.textColor = [UIColor darkGrayColor];
text.textAlignment =NSTextAlignmentCenter;
// create imageView
UIImageView *lblView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 325, 280, 240)];
// set label
[lblView addSubview:text];
// apply tag to access in future
lblView.tag=i+1;
// add to scrollView
[scrMain addSubview:lblView];
}
我有一个如何使用UIImageView
:的例子
for (int i=1; i<=3; i++) {
// create image
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"sti%02i.png",i]];
// create imageView
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width + 23, 60, 280, 260)];
// set scale to fill
imgV.contentMode=UIViewContentModeScaleToFill;
// set image
[imgV setImage:image];
// apply tag to access in future
imgV.tag=i+1;
// add to scrollView
[scrMain addSubview:imgV];
}
这些图像在我的项目中,编号为sti01、sti02等等……然后对每个图像按一计数,然后将它们加载到滚动视图中。我希望这能有所帮助!
标签的y位置应根据索引进行调整。
您可以使用数组计数,而不是固定的"3"。
您不需要介于两者之间的UIImageView。
你可以试试这个:
for (int i = 0; i < self.array.count; i++) {
// create label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, i*30, self.view.frame.size.width,30)];
label.text = [self.array objectAtIndex:i];
label.font = [UIFont fontWithName:@"HelveticaNeueLTStd-LtCn" size:15];
label.textColor = [UIColor darkGrayColor];
label.textAlignment = NSTextAlignmentCenter;
// add to scrollView
[scrMain addSubview:label];
}
如果我理解正确,您需要进行以下更改:
text.text = [NSString stringWithFormat:@"%@", [self.array objectAtIndex:i]];
这将从字符串数组中提取第i
个对象,并将其设置为UILabel
的文本。
为什么不循环遍历数组,而不是像这样尝试将文本分配给整个数组:
for (int i=0; i<3; i++) {
// create label
UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,30)];
text.text = [NSString stringWithFormat:@"%@", [self.array objectAtIndex:i]];
text.font=[UIFont fontWithName:@"HelveticaNeueLTStd-LtCn" size:15];
text.textColor = [UIColor darkGrayColor];
text.textAlignment =NSTextAlignmentCenter;
// create imageView
UIImageView *lblView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 325, 280, 240)];
// set label
[lblView addSubview:text];
// apply tag to access in future
lblView.tag=i+1;
// add to scrollView
[scrMain addSubview:lblView];
}
这样,您只需拉出一个字符串,将其指定为UILabel的文本,然后将其作为子视图添加到相应的imageView中。