RootView.m
#import "RootView.h"
#define YHColor [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1] @implementation RootView - (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self add];
}
return self;
} - (void)add { // 添加滚动
self.scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
self.scrollView.backgroundColor = YHColor;
//self.scrollView.contentSize = CGSizeMake(self.frame.size.width * 10, 0); [self addSubview:self.scrollView]; // 添加图片 self.imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"002.jpg"]]; // 用此方法就不用设置frame,因为frame就是图片的大小
[self.scrollView addSubview:self.imgView]; self.scrollView.contentSize = self.imgView.frame.size; //设置滚动范围(根据图片尺寸滚动) self.scrollView.showsHorizontalScrollIndicator = NO; // 隐藏垂直滚动条
self.scrollView.showsVerticalScrollIndicator = NO; // 隐藏水平滚动条 self.scrollView.bounces = YES; // 设置是否回弹
// self.scrollView.alwaysBounceHorizontal = NO; // 设置水平方向是否回弹(必须要设置滚动范围是屏幕大小,否则不起作用)
// self.scrollView.alwaysBounceVertical = YES; // 设置垂直方向是否回弹(必须要设置滚动范围是屏幕大小,否则不起作用) // self.scrollView.contentSize = CGSizeMake(self.imgView.frame.size.width, 0); // 只要水平滚动
// self.scrollView.contentSize = CGSizeMake(0, self.imgView.frame.size.height); // 只要垂直滚动 // 设置偏移量,规定要显示的位置
self.scrollView.contentOffset = CGPointMake(, ); // 设置缩放
self.scrollView.minimumZoomScale = 0.1; // 设置最小比例
self.scrollView.maximumZoomScale = ; // 设置最大比例
//self.scrollView.zoomScale = 1; // 设置当前缩放比例(不能在这里设置,要在viewController里设置才行)
}
@end
RootViewController.m
#import "RootViewController.h"
#import "RootView.h" @interface RootViewController () <UIScrollViewDelegate> @property (nonatomic, strong) RootView *rootView; @end @implementation RootViewController - (void)loadView {
self.rootView = [[RootView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.view = self.rootView;
} - (void)viewDidLoad {
[super viewDidLoad]; // 设置代理
self.rootView.scrollView.delegate = self; // 当前缩放比例
self.rootView.scrollView.zoomScale = 0.5; } #pragma mark - 实现协议方法(监测滚动状态)
// 即将开始滚动
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
NSLog(@"开始滚动");
} // 滚动完成
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(@"结束滚动");
} // 即将开始手动拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
NSLog(@"即将开始手动拖拽");
} // 手动拖拽完成
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
NSLog(@"手动拖拽完成");
} // 一直滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(@"一直滚动%f", scrollView.contentOffset.x);
} #pragma mark - 视图缩放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { // 返回要缩放的视图
return self.rootView.imgView;
} // 缩放完成,把图片设置为中间位置
- (void)scrollViewDidZoom:(UIScrollView *)scrollView { self.rootView.imgView.center = self.view.center;
} @end