IOS UIScrollView——简单示例

头文件:

@interface STScrollViewController ()<UIScrollViewDelegate>{
    @private
    UIScrollView *mScrollView;
    // 记录view drag的位置
    CGPoint offset;
    // 判断是否结束drag
    BOOL endDragging;
}

@end

类文件:

- (void)viewDidLoad {
    [super viewDidLoad];
    endDragging = NO;
    mScrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    mScrollView.backgroundColor = [UIColor redColor];
    mScrollView.delegate = self;
    // 设置scrollview显示内容大小
    mScrollView.contentSize = mScrollView.frame.size;
    // 多屏时,是否分页显示
    mScrollView.pagingEnabled = YES;
    // 设置滚动条的属性
    mScrollView.alwaysBounceHorizontal = YES;
    mScrollView.alwaysBounceVertical = YES;
    mScrollView.showsHorizontalScrollIndicator = YES;
    mScrollView.showsVerticalScrollIndicator = YES;
    // 设置混动条颜色风格
    mScrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault;
    [self.view addSubview:mScrollView];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 100)];
    label.backgroundColor = [UIColor yellowColor];
    label.text = @"Test for scrolleview";
    [mScrollView addSubview:label];
}

在UIScrollView的代理回调中实现了拖动效果:

// scrollView 已经滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewDidScroll");
    if (endDragging) {
        mScrollView.contentOffset = offset;
    }  
}
// scrollView 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewWillBeginDragging");
    endDragging = NO;
}
// scrollView 结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    offset = scrollView.contentOffset;
    endDragging = YES;
    NSLog(@"scrollViewDidEndDragging offset x= %f  y=%f",offset.x,offset.y);  
}

UIScrollView的一些属性:

IOS UIScrollView——简单示例_第1张图片

UIScrollViewDelegate的一些回调函数:

IOS UIScrollView——简单示例_第2张图片

你可能感兴趣的:(IOS)