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−

通过添加 < 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.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
}

输出

运行应用程序后,我们将获得以下输出。滚动滚动视图后,即可看到图像的其余部分。

iOS Tutorial
ios_ui_elements.htm
广告