您好我的应用程序中我想在UIScrollView中的每个图像上显示不同的标签文本。 这是我的代码。
for (int i=0; i<imageArray.count; i++)
{
NSString *str = [imageArray objectAtIndex:i];
NSString *bannerImageURL = [NSString stringWithFormat:@"http://url.com", str];
CGFloat myOrigin = i * self.view.frame.size.width;
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(myOrigin, 0, self.view.frame.size.width,imgScrollView.frame.size.height)];
myImageView.contentMode = UIViewContentModeScaleToFill;
myImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:bannerImageURL]]];
imgScrollView.contentSize = CGSizeMake(self.view.frame.size.width * imageArray.count, self.view.frame.size.height);
CGPoint scrollPoint = CGPointMake(0, 0);
[imgScrollView setContentOffset:scrollPoint animated:YES];
imgScrollView.delegate = self;
[imgScrollView addSubview:myImageView];
}
这是我的代表方法。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[imgScrollView setContentOffset: CGPointMake(imgScrollView.contentOffset.x,0)];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
NSLog(@"Scrolling - You are now on page %i",page);
}
我想将数组传递给该标签,还有一件事如何将页面控制器添加到此代码中? 请帮助。
答案 0 :(得分:2)
我不确定你在上述问题中指的是什么标签。我假设您的标头中定义了标签UILabel * _label
和数组NSArray * _namesArray
。
我试图稍微清理你的代码。试试这个:
for(int index = 0; index < [imageArray count]; index++){
NSString * string = [imageArray objectAtIndex:index];
NSString * bannerImageURL = [NSString stringWithFormat:@"http://url.com/%@", string]; // You weren't using the string in your formatter, so I added it to the end.
CGFloat myOrigin = index * self.view.frame.size.width;
UIImageView * myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(myOrigin, 0.0f, self.view.frame.size.width, imageScrollView.frame.size.height)];
myImageView.contentMode = UIViewContentModeScaleToFill;
myImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:bannerImageURL]]];
[imageScrollView addSubview:myImageView];
}
imageScrollView.contentSize = CGSizeMake(self.view.frame.size.width * imageArray.count, self.view.frame.size.height);
[imageScrollView setContentOffset:CGPointZero animated:YES];
imageScrollView.delegate = self;
然后对于委托方法,您将尝试:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView; {
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
_label.text = [_namesArray objectAtIndex:page];
NSLog(@"Scrolling - You are now on page %i, and the name for the label is: %@", page, [_namesArray objectAtIndex:page]);
}
希望有帮助!