对于Scroll views一个最基础的问题就是content size。Scroll view将严格按照这个size来展示其内容。
展示一个size大于screen的图片:
头文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIScrollViewDelegate>
@property (strong,nonatomic) UIImageView *imageView;
@property (nonatomic,strong) UIScrollView *myScrollView;
@end
实现
#import "ViewController.h"
@interfaceViewController ()
@end
@implementation ViewController
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
/* Gets called when user scrolls or drags */
self.myScrollView.alpha = 0.50f;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
/* Gets called only after scrolling */
self.myScrollView.alpha = 1.0f;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
/* Make sure the alpha is reset even if the user is dragging */
self.myScrollView.alpha = 1.0f;
}
- (void)viewDidLoad
{
[superviewDidLoad];
UIImage *image = [UIImage imageNamed:@"viewImage"];
self.imageView = [[UIImageView alloc] initWithImage:image];
self.myScrollView = [[UIScrollViewalloc] initWithFrame:self.view.bounds];
[self.myScrollViewaddSubview:self.imageView];
self.myScrollView.contentSize = self.imageView.bounds.size;
self.myScrollView.delegate = self;
self.myScrollView.indicatorStyle =UIScrollViewIndicatorStyleDefault; //scroll的样式
[self.viewaddSubview:self.myScrollView];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
@end
scroll views最大的特点就是可以标记页码:
- (UIImageView *) newImageViewWithImage:(UIImage *)paramImage
frame: (CGRect)paramRect {
UIImageView *resule = [[UIImageView alloc]initWithImage:paramImage];
resule.frame = paramRect;
return resule;
}
- (void)viewDidLoad
{
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
UIImage *iPhone = [UIImage imageNamed:@"iPhone.png"];
UIImage *iPad = [UIImage imageNamed:@"iPad.png"];
UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
CGRect scrollViewRect = self.view.bounds;
self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollViewRect];
self.myScrollView.pagingEnabled = YES;
self.myScrollView.contentSize = CGSizeMake(scrollViewRect.size.width * 3.0f,scrollViewRect.size.height);
[self.viewaddSubview:self.myScrollView];
CGRect imageViewRect = self.view.bounds;
UIImageView *iPhoneImageView = [self newImageViewWithImage:iPhone frame:imageViewRect];
[self.myScrollView addSubview:iPhoneImageView];
/* Go to next page by moving the x position of the next image view */
imageViewRect.origin.x += imageViewRect.size.width;
UIImageView *iPadImageView = [self newImageViewWithImage:iPad
frame:imageViewRect];
[self.myScrollView addSubview:iPadImageView];
/* Go to next page by moving the x position of the next image view */
imageViewRect.origin.x += imageViewRect.size.width;
UIImageView *macBookAirImageView =
[self newImageViewWithImage:macBookAir frame:imageViewRect];
[self.myScrollView addSubview:macBookAirImageView];
}