我有一个 UIScrollView 显示三个图像(目前是两个 UIImage 和一个 UIColor,因为我还没有收到第三个图形),并且我一直在尝试添加 UIPageControl 但遇到了一些问题。
我需要 UIPageControl 有一个透明的背景(这在 IB 中很容易),然后让它位于 UIScrollView 的顶部并显示用户所在的页面。
第一个问题是 UIPageControl 位于 UIScrollView 后面。 第二个问题是,当您尝试进入第二页时,它会滚动第一页(如果我用文本输出图像并且它在其后面可见)。 第三个问题是我相信它不会显示用户所在的页面(尽管它可能有效,但由于第二个问题我无法看到!)
我对 XCode 相当陌生,但已经使用它几个星期了,所以我不是一个完全的业余爱好者。我一直在寻找解决这个问题的方法有一段时间了,但似乎找不到其他任何东西。抱歉,如果这个问题以前曾出现过但我只是没有找到它!
这是我的代码:
HomeViewController.h
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController {
UIScrollView *scrollView;
UIPageControl *pageControl;
}
@property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
@property (nonatomic, retain) IBOutlet UIPageControl *pageControl;
@end
HomeViewController.m
#import "HomeViewController.h"
@implementation HomeViewController
@synthesize scrollView;
@synthesize pageControl;
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor colorWithPatternImage:[UIImage imageNamed:@"SuperflyPoster_1.jpg"]], [UIColor colorWithPatternImage:[UIImage imageNamed:@"SuperflyPoster_2.jpg"]], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width *i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [colors objectAtIndex:i];
[self.scrollView addSubview:subview];
[subview release];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width *colors.count, self.scrollView.frame.size.height);
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.scrollView = nil;
}
- (void)dealloc {
[pageControl release];
[scrollView release];
[super dealloc];
}
@end
非常感谢。
真诚的,您遇到的问题也是我遇到的问题。所以,我写了一个PagedImageScrollView来简化它,也许你也可以学习一下,这是链接
希望能有所帮助。玩得开心。
虽然这篇文章相当老了,而且由于我在这里寻求帮助并后来自己解决了问题,我认为答案可能会对其他人有所帮助。
问题1和2:第一和第二个问题的原因是因为当您将UIPageControl拖到故事板中时,您可能将其放在滚动视图上,这使其成为滚动视图的子视图。当你向滚动视图中添加图像或其他内容后,新的内容将覆盖 UIPageControl,并且由于 pageControl 是滚动视图的子视图,因此它会随着内容滚动,并滚动到屏幕之外。
解决方案 1 和 2:您应该将 UIPageControl 和 ScrollView 与 Controller 的基本 View 的子视图放在同一级别,并且 UIPageControl 应出现在“文档大纲”中 UIScrollview 的下方(文档大纲中的下方意味着在文档大纲中的前面)看法)。为此,您可能需要先拖动 UIPageControl,然后拖动滚动视图,调整滚动视图的大小,然后在“文档大纲”中切换它们的位置。
问题3:看来你正确设置了pageControl的页面,如果你可以看到你的pagecontrol,它可能已经工作了。并且您应该将scrollView的启用分页设置为YES。