我已经下载了这个项目,展示了一个关于分页的小例子:
分页示例项目
我添加了一个标签,并使用 scrollViewDidScroll: 发生任何滚动操作时调用的委托方法,我调用了一个重置我添加的标签的 x 位置的方法。如果我在收到 x 位置时让它,那么位置变化会按预期发生,但如果我将收到的参数值恢复为负,则它不起作用。
这是代码:.h 文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIScrollViewDelegate>
- (void)pageChanged ;
@end
和 .m 文件: #import "ViewController.h"
@interface ViewController (){
UIPageControl *pageControl;
UIScrollView *scroll;
UILabel *myLabel;
int curentLabelX;
int initialLabelX;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor=[UIColor clearColor];
// Scroll View
scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
scroll.backgroundColor=[UIColor clearColor];
scroll.delegate=self;
scroll.pagingEnabled=YES;
[scroll setContentSize:CGSizeMake(scroll.frame.size.width*3, scroll.frame.size.height)];
// page control
pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 424, 320, 36)];
pageControl.backgroundColor=[UIColor blackColor];
pageControl.numberOfPages=3;
[pageControl addTarget:self action:@selector(pageChanged) forControlEvents:UIControlEventValueChanged];
pageControl.alpha = 0;
CGFloat x=0;
for(int i=1;i<4;i++)
{
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(x+0, 0, 320, 460)];
[image setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image%d.jpg",i]]];
[scroll addSubview:image];
x+=320;
}
[self.view addSubview:scroll];
[self.view addSubview:pageControl];
initialLabelX = 100;
myLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
myLabel.backgroundColor = [UIColor redColor];
[self.view addSubview:myLabel];
}
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView{
// NSLog(@"%@", _scrollView);
CGFloat viewWidth = _scrollView.frame.size.width;
// content offset - tells by how much the scroll view has scrolled.
int pageNumber = floor((_scrollView.contentOffset.x - viewWidth/50) / viewWidth) +1;
pageControl.currentPage=pageNumber;
int myLabelContentOffset = _scrollView.contentOffset.x;
NSLog(@"Scroll offset: %d", myLabelContentOffset);
[self changeLabelOffset:myLabelContentOffset];
}
- (void)changeLabelOffset:(int) byScrollView{
curentLabelX = byScrollView;
curentLabelX = -curentLabelX;
NSLog(@"Label X pos: %d", initialLabelX + curentLabelX);
[myLabel setFrame:CGRectMake(initialLabelX + curentLabelX, 100, 100, 100)];
}
- (void)pageChanged {
int pageNumber = (int)pageControl.currentPage;
CGRect frame = scroll.frame;
frame.origin.x = frame.size.width*pageNumber;
frame.origin.y=0;
[scroll scrollRectToVisible:frame animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[super viewDidUnload];
}
@end
问题是标签与滚动同时改变位置和速度,因此它出现是正常的,因为它根本不移动。