如果内容超出屏幕的大小就会使用到滚动视图来显示隐藏的部分。
它可以包含所有的其他用户界面元素 如图像视图、 标签、 文本视图甚至另一个滚动视图。
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
在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.accessibilityActivationPoint = CGPointMake(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"到我们的项目,可以通过将图像拖到我们导航区域,其中列出了我们的项目文件所做的图像。图像应高于设备的高度。
-(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"); }
(void)viewDidLoad { [super viewDidLoad]; [self addScrollView]; //Do any additional setup after loading the view, typically from a nib }
现在当我们运行该应用程序我们会看到下面的输出。一旦滚动滚动视图,将能够查看图像的其余部分: