普通的 UIView 不具有滾動功能,不能顯示過多的內容。UIScrollView 是一個可以滾動的視圖控件,可用來展現大量的內容。html
UIScrollView 的簡單使用:atom
1)將須要展現的內容添加到 UIScrollView 中;spa
2)設置 UIScrollView 的 contentSize 屬性,指定可滾動的範圍。code
可用屬性:htm
1) @property(nonatomic) CGPoint contentOffset; 表示 UIScrollView 滾動的位置。blog
2) @property(nonatomic) CGSize contentSize; 表示 UIScrollView 的滾動範圍。開發
3) @property(nonatomic) UIEdgeInsets contentInset; 在 UIScrollView 的四周增長額外的滾動區域。get
4) @property(nonatomic) BOOL bounces; 設置 UIScrollView 是否須要彈簧效果。博客
5) @property(nonatomic, getter=isScrollEnabled) BOOL scrollEnabled; 設置 UIScrollView 是否能滾動。it
6) @property(nonatomic) BOOL showsHorizontalScrollIndicator; 是否顯示水平滾動條。
7) @property(nonatomic) BOOL showsVerticalScrollIndicator; 是否顯示垂直滾動條。
以下爲幾個屬性表明的座標示意圖:
1) UIScrollView 的 frame 指可視範圍, contentSize 是滾動範圍。
2) contentSize 屬性只能使用代碼設置。
實例演示:
新建一個Single View Application,在 ViewController 類擴展中添加一個私有的 UIScrollView 屬性,代碼以下:
1 //ViewController.m 2 @interface ViewController () 3 { 4 UIScrollView *_scrollView; 5 } 6 @end
修改 viewDidLoad 方法,實現 UIScrollView 的添加與顯示:
1 //ViewController.m 2 - (void)viewDidLoad { 3 [super viewDidLoad]; 4 //建立UIScrollView 5 UIScrollView *scrollView = [[UIScrollView alloc] init]; 6 scrollView.frame = CGRectMake(0, 0, 250, 250); 7 scrollView.backgroundColor = [UIColor grayColor]; 8 [self.view addSubview:scrollView]; 9 10 //建立UIImageView 11 UIImageView *imageView = [[UIImageView alloc] init]; 12 imageView.image = [UIImage imageNamed:@"picture.jpg"]; 13 CGFloat imageWidth = imageView.image.size.width; 14 CGFloat imageHeight = imageView.image.size.height; 15 imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight); 16 [scrollView addSubview:imageView]; 17 18 //設置UIScrollView的屬性 19 scrollView.contentSize = imageView.image.size; 20 scrollView.showsHorizontalScrollIndicator = YES; 21 scrollView.showsVerticalScrollIndicator = YES; 22 scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20); 23 _scrollView = scrollView; 24 }- (void)viewDidLoad { 25 [super viewDidLoad]; 26 //建立UIScrollView 27 UIScrollView *scrollView = [[UIScrollView alloc] init]; 28 scrollView.frame = CGRectMake(0, 0, 250, 250); 29 scrollView.backgroundColor = [UIColor grayColor]; 30 [self.view addSubview:scrollView]; 31 32 //建立UIImageView 33 UIImageView *imageView = [[UIImageView alloc] init]; 34 imageView.image = [UIImage imageNamed:@"picture.jpg"]; 35 CGFloat imageWidth = imageView.image.size.width; 36 CGFloat imageHeight = imageView.image.size.height; 37 imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight); 38 [scrollView addSubview:imageView]; 39 40 //設置UIScrollView的屬性 41 scrollView.contentSize = imageView.image.size; 42 scrollView.showsHorizontalScrollIndicator = YES; 43 scrollView.showsVerticalScrollIndicator = YES; 44 scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20); 45 _scrollView = scrollView; 46 }