我感兴趣的是使用页面控件来切换数组中的条目而不更改视图。我怎样才能做到这一点?有没有教程。 。 。
但是,无论何时切换页面,背景颜色和一些图像都会发生变化。切换页面后有没有办法运行代码?
由于
答案 0 :(得分:3)
UIPageControl
只有表示分页,它不管理分页行为本身。单击UIPageControl
时,您需要编写自己的代码来遍历数组。 currentPage
属性应设置为您在数组中使用的索引,totalPages
属性应设置为数组的count
属性。最后,您需要使用-addTarget:action:forControlEvents:
UIControlEventValueChanged
事件设置目标/操作对
[pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
当用户点击页面控件移动到下一页或上一页时,控件会发送 UIControlEventValueChanged 事件以供委托人处理。然后,委托可以评估currentPage属性以确定要显示的页面。页面控件在任一方向上只前进一页。
因此,您可以使用该事件来确定页面何时更改。
示例:
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (strong, nonatomic) NSArray *items;
[...]
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.items = [NSArray arrayWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Ten", nil];
[self.pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
// Left Swipe to go to previous page
UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(previousPage:)];
leftSwipeGestureRecognizer.direction = numberOfTouchesRequired = 1;
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:leftSwipeGestureRecognizer];
// Right Swipe to go to next page
UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nextPage:)];
rightSwipeGestureRecognizer.direction = numberOfTouchesRequired = 1;
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:rightSwipeGestureRecognizer];
}
- (void)previousPage:(UISwipeGestureRecognizer *)swipeGestureRecognizer
{
self.pageControl.currentPage = self.pageControl.currentPage-1;
}
- (void)nextPage:(UISwipeGestureRecognizer *)swipeGestureRecognizer
{
self.pageControl.currentPage = self.pageControl.currentPage+1;
}
- (void)pageChanged:(id)sender
{
NSString *selectedItem = [self.items objectAtIndex:self.pageControl.currentPage];
NSLog(@"\nSelected Item: %@\nCurrent Page: %d\nTotal Number of Pages: %d\n", selectedItem, self.pageControl.currentPage+1, self.pageControl.numberOfPages);
}
单击页面控件时,它会向前或向后移动self.items
属性表示的字符串数组。 -pageChanged:
也是您更新视图控件的地方。
如果要更新其他区域的UIPageControl中的当前页面,只需执行以下操作:
self.pageControl.currentPage = 5; // set to whatever page you need represented