iOS - 滚动视图
使用滚动视图
滚动视图用于显示超出屏幕大小的内容。 它可以包含所有其他 UI 元素,例如图像视图、标签、文本视图,甚至是另一个滚动视图本身。
重要属性
- contentSize
- contentInset
- contentOffset
- delegate
重要方法
实例
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
- (void)setContentOffset:(CGPoint)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 如下−
Make your class conform to scroll view delegate protocol by adding < UIScrollViewDelegate> and declaring a scroll view instance as shown below in 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" 的图像添加到我们的项目中,这可以通过将图像拖到列出项目文件的导航器区域来完成。 图像的分辨率应高于设备以查看图像的滚动。
在 ViewController.m 中实现 scrollView 委托
实例
-(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
}
输出
当我们运行应用程序时,我们将得到以下输出。 滚动视图后,您将能够看到图像的剩余部分。