iPhone: uiscrollview пейжинг включен без zoom и без предварительного просмотра

StackOverflow https://stackoverflow.com/questions/3923197

Вопрос

Я хочу реализовать UISCROLLVIEW, в котором включен пейджинг, и я могу просто щедрости через некоторые изображения. Вот все, что я хочу иметь возможность сделать сейчас.

Я сделал это до сих пор в интерфейсе Builder: можете ли кто-нибудь помочь?

alt text

Я не знаю, как сделать все остальное. Может кто-нибудь, пожалуйста, помогите мне с этим. Мне не нужна никакая функциональность масштабирования. Я не хочу предварительного просмотра предыдущего или следующего изображения в ScrollView, я просто хочу прокрутить просмотр прокрутки прокрутки подкачки, который позволяет пользователю щелкнуть изображениями.

Вся помощь ценится. Если бы вы могли сказать мне шаг за шагом, как я мог достичь этого, что было бы наиболее ценным. благодарю вас.

Я посмотрел на примеры кода, и у них просто слишком много сложности происходит. Я посмотрел на несколько и предпочитаю учебное пособие с самого начала. благодарю вас

Это было полезно?

Решение

Похоже, вам просто нужно добавить свой контент в качестве субвезонного использования UISCROLLVIEW и добавить распознатель жеста.

Загрузите изображение в UiimageView. Добавьте UiimageView в качестве субвезонного представления UISCROLLVIEW.

// do this in init or loadView or viewDidLoad, wherever is most appropriate
// imageView is a retained property
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"];
[scrollView addSubview:imageView];

Добавьте UiswipeGestureCognizer в UiscrollView.

// probably after the code above
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:);
[scrollView addGestureRecognizer:swipe];
[swipe release];

На обработчике UiswipegestureCognizer измените загруженный образ в UiimageView.

- (void)handleSwipe:(UIGestureRecognizer *)swipe {
  // do what you need to determine the next image
  imageView.image = [UIImage imageNamed:<your replacement image here>];
}

Другие советы

Может быть, вы хотите взглянуть на мой Образец реализации ViewController, который делает точным. Я написал эту вещь как ответ на этот вопрос.
Может быть, это слишком сложно для вас, но это не будет легче.
И это только базовая версия, которая загружает все изображения в память в начале. Это не будет работать в реальном применении. Таким образом, вы должны реализовать некоторые функции UiscrollView-делегата. И там начинается сложность ...

//  ImageViewController.h
//
//  Created by Matthias Bauch on 12.10.10.
//  Copyright 2010 Matthias Bauch. All rights reserved.
//

#import <UIKit/UIKit.h>

#warning this is just a quick hack, you should not use this if you dont understand this. There might be leaks, bugs and a lot of whatever.

@interface ImageViewController : UIViewController {
    NSString *imagePath;
}
@property (nonatomic, copy) NSString *imagePath;
- (id)initWithImageDirectory:(NSString*)imgPath;
@end


//
//  ImageViewController.m
//
//  Created by Matthias Bauch on 12.10.10.
//  Copyright 2010 Matthias Bauch. All rights reserved.
//

#import "ImageViewController.h"


@implementation ImageViewController
@synthesize imagePath;

- (id)initWithImageDirectory:(NSString*)imgPath {
    if (self = [super init]) {
        imagePath = [imgPath copy];
    }
    return self;
}


- (UIView *)viewFullOfImagesAtPath:(NSString *)path withSize:(CGSize)size {
    NSError *error = nil;
    NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
    if (!filenames) {
        NSLog(@"Error accessing files: %@ [%@]", [error localizedDescription], error);
        return nil;
    }
    UIView *aView = [[UIView alloc] init];
    CGFloat xOffset = 0;
    for (NSString *filename in filenames) {
        NSString *fullPath = [path stringByAppendingPathComponent:filename];
        UIImage *image = [[[UIImage alloc] initWithContentsOfFile:fullPath] autorelease];
        if (!image)
            continue;
        CGRect frameRect = CGRectMake(xOffset, 0, size.width, size.height);
        UIImageView *imageView = [[[UIImageView alloc] initWithFrame:frameRect] autorelease];
        [imageView setImage:image];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [aView addSubview:imageView];
        xOffset += size.width;
    }
    aView.frame = CGRectMake(0, 0, xOffset, size.height);
    return [aView autorelease];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIScrollView *scrollView = [[[UIScrollView alloc] initWithFrame:self.view.bounds] autorelease];
    scrollView.pagingEnabled = YES;
    UIView *contentView = [self viewFullOfImagesAtPath:imagePath withSize:CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height)];
    NSLog(@"%f %f %f %f", contentView.frame.origin.x, contentView.frame.origin.y, contentView.frame.size.width, contentView.frame.size.height);
    [scrollView addSubview:contentView];
    scrollView.contentSize = CGSizeMake(CGRectGetWidth(contentView.frame), CGRectGetHeight(contentView.frame));
    [self.view addSubview:scrollView];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [imagePath release];
    [super dealloc];
}


@end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top