使用Scroll View
滚动视图用于显示内容超过屏幕大小。它可以包含所有其他用户界面元素,如图像视图,标签,文本视图,甚至是另一个滚动视图本身。
重要的属性
-
contentSize
-
contentInset
-
contentOffset
-
delegate
重要的方法
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
- (void)setContentOffset:(CGYiibai)contentOffset animated:(BOOL)animated
重要的委托方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
更新ViewController.h 如下:
让类符合滚动视图委托协议通过添加<UIScrollViewDelegate>声明滚动视图实例如下图所示,在ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIScrollViewDelegate> { UIScrollView *myScrollView; } @end
添加一个自定义的方法addScrollView
-(void)addScrollView{ myScrollView = [[UIScrollView alloc]initWithFrame: CGRectMake(20, 20, 280, 420)]; myScrollView.accessibilityActivationYiibai = CGYiibaiMake(100, 100); imgView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"AppleUSA.jpg"]]; [myScrollView addSubview:imgView]; myScrollView.minimumZoomScale = 0.5; myScrollView.maximumZoomScale = 3; myScrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height); myScrollView.delegate = self; [self.view addSubview:myScrollView]; }
注意事项:
我们必须命名为 “AppleUSA1.jpg”,我们可以通过拖动图像到我们的导航区域,项目文件列出的项目中添加图像。图像的分辨率高于设备看到的图像的滚动。
实现滚动视图在 ViewController.m 委托
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{ return imgView; } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ NSLog(@"Did end decelerating"); } -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ // NSLog(@"Did scroll"); } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ NSLog(@"Did end dragging"); } -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{ NSLog(@"Did begin decelerating"); } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ NSLog(@"Did begin dragging"); }
更新 ViewController.m 中的 viewDidLoad 方法如下
(void)viewDidLoad { [super viewDidLoad]; [self addScrollView]; //Do any additional setup after loading the view, typically from a nib }
输出
现在,当我们运行程序时,我们会得到下面的输出。一旦滚动滚动视图,将能够看到图像的其余部分。