手機螢幕再大也有極限,當內容超出一個視窗時,使用者只能靠滑動手勢來看見其餘部分。普通的 UIView 並不具備滾動能力,而 UIScrollView 正是為此而生——它同時也是 UITableView 與 UICollectionView 的父類別,學好它就等於掌握了半個 iOS 列表體系。
典型場景就是手機「設定」頁面,內容遠超一個螢幕,靠上下滑動瀏覽。
UIScrollView。contentSize,告訴它所有內容的整體尺寸——也就是滾動的邊界,能滾多遠、到哪裡是盡頭。三個最核心的:
@property (nonatomic) CGPoint contentOffset; // 當前滾動位置 @property (nonatomic) CGSize contentSize; // 內容尺寸,決定滾動範圍 @property (nonatomic) UIEdgeInsets contentInset; // 在四周增加額外可滾動區域
其他實用屬性:
@property (nonatomic) BOOL bounces; // 是否啟用彈簧(橡皮筋)效果 @property (nonatomic, getter=isScrollEnabled) BOOL scrollEnabled; // 是否可滾動 @property (nonatomic) BOOL showsHorizontalScrollIndicator; // 是否顯示水平滾動條 @property (nonatomic) BOOL showsVerticalScrollIndicator; // 是否顯示垂直滾動條
#import "MJViewController.h"
@interface MJViewController ()
{
UIScrollView *_scrollView;
}
@end
@implementation MJViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 建立 UIScrollView
UIScrollView *scrollView = [[UIScrollView alloc] init];
// frame 的 size 就是「可視範圍」
scrollView.frame = CGRectMake(0, 0, 250, 250);
scrollView.backgroundColor = [UIColor grayColor];
[self.view addSubview:scrollView];
// 2. 放入一張大圖
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:@"big.jpg"];
CGFloat imgW = imageView.image.size.width;
CGFloat imgH = imageView.image.size.height;
imageView.frame = CGRectMake(0, 0, imgW, imgH);
[scrollView addSubview:imageView];
// 3. 設定屬性
// 滾動範圍=內容尺寸
scrollView.contentSize = imageView.image.size;
// 隱藏兩個方向的滾動條
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
// 增加額外滾動區域(逆時針:上、左、下、右)
scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20);
_scrollView = scrollView;
}
// 用動畫往下捲 150pt
- (IBAction)down:(UIButton *)sender
{
[UIView animateWithDuration:1.0 animations:^{
CGPoint offset = _scrollView.contentOffset;
offset.y += 150;
_scrollView.contentOffset = offset;
}];
}
@end
frame 與 contentSize 不是同一件事。frame 是這個 scrollView 在螢幕上「看得見的框」,contentSize 是「裡頭全部內容有多大」。兩者相除就知道總共能滾幾頁。
contentInset 只能擴邊,不能縮小。它的四個值依序是 top、left、bottom、right(逆時針)。可以用程式碼設定,也可以在 Storyboard 設定,但兩者容易互相覆蓋,混用時要特別注意。
contentSize 只能用程式碼設定。Storyboard 沒有提供直覺入口,這是新手常找不到的地方。
結構體屬性不能「直接改成員」。像 scrollView.contentSize.width = 100; 這種寫法是不允許的,必須走三步:先取出值 → 修改 → 再賦回去。
CGSize size = scrollView.contentSize; size.width = 100; scrollView.contentSize = size;
contentSize(或設得比 frame 還小)。scrollEnabled = NO。userInteractionEnabled = NO。contentSize 會被約束系統干擾,導致滾動範圍不如預期。