带有图像的 UIScrollView

是否可以使用 UIScrollView 来查看大约 800px 长的图像?我尝试使用 UIScrollView 和 UIImageView 但它没有滚动。有人可以帮忙吗?

stack overflow UIScrollView with image
原文答案

答案:

作者头像
@interface ZoomViewController : UIViewController <uiscrollviewdelegate> {

    IBOutlet UIScrollView *scroll;
    UIImageView *image;
}

@property (nonatomic, retain) UIScrollView *scroll;

@end
</uiscrollviewdelegate></uikit>

一旦检查您的 Viewdidload 方法。

- (void)viewDidLoad {

       image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img_body.png"]];

        [super viewDidLoad];

    image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img_body.png"]];

    scroll.contentSize = image.frame.size;

    [scroll addSubview:image];

    scroll.minimumZoomScale = 0.4;

    scroll.maximumZoomScale = 4.0;

    scroll.delegate = self;
    [scroll setZoomScale:scroll.minimumZoomScale];
    [super viewDidLoad];

}
作者头像

采用:

UIScrollView *yourScrollview = [[UIScrollView alloc] initWithFrame:(CGRect){{0,0}, {320,480}}];

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourImageHere.png"]];
yourImageView.frame = yourScrollview.bounds;

yourScrollview.contentSize = yourImageView.frame.size;
yourScrollview.minimumZoomScale = 0.4;
yourScrollview.maximumZoomScale = 4.0;
[yourScrollview setZoomScale:yourScrollview.minimumZoomScale];
yourScrollview.delegate = self;
[self.view addSubview:yourScrollview];

不要忘记在 .h 文件中添加 UIScrollViewDelegate

注:ARC 代码

作者头像

1。创建一个新项目 -> 单视图应用程序
2.将以下代码放入:

“视图控制器.m”

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void) viewDidLoad
{
    [super viewDidLoad];

    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 
    [scrollView setContentSize:CGSizeMake(320, 800)];

    UIView * myView = [[UIView alloc] initWithFrame : CGRectMake(0, 0, 320, 800)]; 
    UIImageView * myImage = [[UIImageView alloc]initWithImage : [UIImage imageNamed:@"Test.png"]];
    [myView addSubview: myImage];
    [myImage release];
    [scrollView addSubview: myView];
    [myView release];

    [self.view addSubview: scrollView];
    [scrollView release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
@end

3。将图像“Test.png”放入您的项目中(拖放到 Xcode -> 文件夹:支持文件)

作者头像

如果它没有平移,则意味着您忘记设置 contentSize 属性。我的网站上有一个教程,展示了如何在 UIImageView 中嵌入 UIScrollView 并将其设置为平移和缩放。它包括完整的可下载源代码。见 Panning and Zooming with UIScrollView