iOS程序-UIScrollView的使用

2025-12-15 16:38:32

1、#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

- (IBAction)down:(UIButton *)sender;

@end

2、#import "ViewController.h"

@interface ViewController ()

{

    UIScrollView *_scrollView;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    // 1.创建UIScrollView

    UIScrollView *scrollView = [[UIScrollView alloc] init];

    scrollView.frame = CGRectMake(0, 0, 250, 250); // frame中的size指UIScrollView的可视范围

    scrollView.backgroundColor = [UIColor grayColor];

    [self.view addSubview:scrollView];

    

    // 2.创建UIImageView(图片)

    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的属性

    

    // 设置UIScrollView的滚动范围(内容大小)

    scrollView.contentSize = imageView.image.size;

    

    // 隐藏水平滚动条

    scrollView.showsHorizontalScrollIndicator = NO;

    scrollView.showsVerticalScrollIndicator = NO;

    

    // 用来记录scrollview滚动的位置

    scrollView.contentOffset = CGPointMake(200, 200);

    

    // 去掉弹簧效果

    scrollView.bounces = NO;

    

    // 增加额外的滚动区域

    // top  left  bottom  right

    scrollView.contentInset = UIEdgeInsetsMake(20, 20, 20, 20);

    

    _scrollView = scrollView;

}

- (IBAction)down:(UIButton *)sender

{

    [UIView animateWithDuration:1.0 animations:^{

        CGPoint offset = _scrollView.contentOffset;

        offset.y += 150;

        _scrollView.contentOffset = offset;

        

//        _scrollView.contentOffset = CGPointMake(0, 0);

    }];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢