通过数组控制页面

时间:2011-10-29 15:11:03

标签: iphone objective-c ios xcode uipagecontrol

我感兴趣的是使用页面控件来切换数组中的条目而不更改视图。我怎样才能做到这一点?有没有教程。 。 。

但是,无论何时切换页面,背景颜色和一些图像都会发生变化。切换页面后有没有办法运行代码?

由于

1 个答案:

答案 0 :(得分:3)

UIPageControl只有表示分页,它不管理分页行为本身。单击UIPageControl时,您需要编写自己的代码来遍历数组。 currentPage属性应设置为您在数组中使用的索引,totalPages属性应设置为数组的count属性。最后,您需要使用-addTarget:action:forControlEvents:

UIControlEventValueChanged事件设置目标/操作对
[pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];

documentation states

  

当用户点击页面控件移动到下一页或上一页时,控件会发送 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