Контроллер просмотра страницы - от изображений к другому контроллеру просмотра

Я немного озадачен тем, чего я пытаюсь достичь. У меня есть контроллер просмотра страниц с источником данных, содержащим список массивов изображений. На самом деле это учебник, который пользователь может пролистать. Что я пытаюсь сделать, так это сделать последнюю страницу экраном входа в систему, чтобы пользователь мог ввести информацию и нажать кнопку входа. Я думал, что это будет так же просто, как добавить контроллер представления входа в массив, но ооо, как же я ошибался D: Когда я попытался это сделать, я получил эту ошибку:

* Завершение работы приложения из-за необработанного исключения "NSInvalidArgumentException", причина: "-[UIViewController _isResizable]: нераспознанный селектор отправлен экземпляру 0xa160660"

Я прошу прощения за то, что я такой нуб, я новичок во всем этом, просто пытаюсь понять это. Вот мой код (на самом деле выполненный с использованием этого сайта):

Мой источник данных (ModelController.h)

#import <Foundation/Foundation.h>
@class DataViewController;
@interface ModelController : NSObject <UIPageViewControllerDataSource>
- (DataViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard   *)storyboard;
- (NSUInteger)indexOfViewController:(DataViewController *)viewController;`
@end

МодельКонтроллер.m

#import "ModelController.h"
#import "DataViewController.h"
#import "LoginViewController.h"

@interface ModelController()
@property (readonly, strong, nonatomic) NSArray *pageData;
@end


@implementation ModelController

- (id)init
{
self = [super init];
if (self)
{

    // Create the data model
    _pageData = [[NSArray alloc] initWithObjects:

                    [UIImage imageNamed:@"tutorial1.png"],
                    [UIImage imageNamed:@"tutorial2.png"],
                    [UIImage imageNamed:@"lastWishes.png"],
                    [UIImage imageNamed:@"todo.png"],
                    [UIImage imageNamed:@"web.png"],
                 (LoginViewController*)[[UIViewController alloc] init],

                     nil];
}
return self;
}

- (DataViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard *)storyboard
{
// Return the data view controller for the given index.
if (([self.pageData count] == 0) || (index >= [self.pageData count]))
{
    return nil;
}

// Create a new view controller and pass suitable data.
DataViewController *dataViewController = [storyboard      instantiateViewControllerWithIdentifier:@"DataViewController"];
dataViewController.dataObject = self.pageData[index];
return dataViewController;
}

- (NSUInteger)indexOfViewController:(DataViewController *)viewController
{
// Return the index of the given data view controller.
// For simplicity, this implementation uses a static array of model objects and the view      controller stores the model object; you can therefore use the model object to identify the index.
return [self.pageData indexOfObject:viewController.dataObject];
}

#pragma mark - Page View Controller Data Source

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController     viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:(DataViewController *)viewController];
if ((index == 0) || (index == NSNotFound)) {
    return nil;
}

index--;
return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController     viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:(DataViewController *)viewController];
if (index == NSNotFound) {
    return nil;
}

index++;
if (index == [self.pageData count]) {
    return nil;
}
return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
}


@end

Родитель (RootViewController.h)

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController <UIPageViewControllerDelegate>

@property (strong, nonatomic) UIPageViewController *pageViewController;

@end

RootViewController.m

#import "RootViewController.h"

#import "ModelController.h"

#import "DataViewController.h"

@interface RootViewController ()
@property (readonly, strong, nonatomic) ModelController *modelController;
@end

@implementation RootViewController

@synthesize modelController = _modelController;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = [[UIPageViewController alloc]   initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl  navigationOrientation:UIPageViewControllerNavigationOrientationVertical options:nil];
self.pageViewController.delegate = self;

DataViewController *startingViewController = [self.modelController viewControllerAtIndex:0 storyboard:self.storyboard];
NSArray *viewControllers = @[startingViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];

self.pageViewController.dataSource = self.modelController;

[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];

// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
CGRect pageViewRect = self.view.bounds;
self.pageViewController.view.frame = pageViewRect;

[self.pageViewController didMoveToParentViewController:self];

// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (ModelController *)modelController
{
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if (!_modelController) {
    _modelController = [[ModelController alloc] init];
}
return _modelController;
}

#pragma mark - UIPageViewController delegate methods

/*
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:    (BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:  (BOOL)completed
{

}
*/

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
// Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
UIViewController *currentViewController = self.pageViewController.viewControllers[0];
NSArray *viewControllers = @[currentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

self.pageViewController.doubleSided = NO;
return UIPageViewControllerSpineLocationMin;
}


@end

Ребенок (DataViewController.h)

#import <UIKit/UIKit.h>

@interface DataViewController : UIViewController
@property (strong, nonatomic) id dataObject;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

DataViewController.m

#import "DataViewController.h"

@interface DataViewController ()

@end

@implementation DataViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.imageView.image = _dataObject;
}

@end

Еще раз, рассматриваемый код находится здесь, где я пытаюсь добавить контроллер представления к источнику данных в качестве последней страницы:

_pageData = [[NSArray alloc] initWithObjects:

                [UIImage imageNamed:@"tutorial1.png"],
                [UIImage imageNamed:@"tutorial2.png"],
                [UIImage imageNamed:@"lastWishes.png"],
                [UIImage imageNamed:@"todo.png"],
                [UIImage imageNamed:@"web.png"],
             (LoginViewController*)[[UIViewController alloc] init],

                 nil];

и получение нераспознанной ошибки селектора во время выполнения. Я также пробовал это:

- (id)init
{
self = [super init];
if (self)
{
    LoginViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    // Create the data model
    _pageData = [[NSArray alloc] initWithObjects:

                    [UIImage imageNamed:@"tutorial1.png"],
                    [UIImage imageNamed:@"tutorial2.png"],
                    [UIImage imageNamed:@"lastWishes.png"],
                    [UIImage imageNamed:@"todo.png"],
                    [UIImage imageNamed:@"web.png"],
                     viewController,

                     nil];
}
return self;
}

Любые предложения были бы замечательными. Спасибо!!


person mafiOSo    schedule 29.10.2012    source источник


Ответы (1)


Ваша идея на 100% верна, ваша реализация нет.

Эта строка:

dataViewController.dataObject = self.pageData[index];

очень подозрительно, потому что это вернет UIViewController в случае вашего экрана входа в систему. Я бы посоветовал вам type-check данные вашей страницы, если это уже подкласс UIViewController, просто верните его, если это (в вашем случае) UIImage, добавьте его как данные объект.

person Paul de Lange    schedule 29.10.2012
comment
Привет Пол. Большое спасибо за ответ на мой пост. Что касается вашего предложения, не могли бы вы добавить небольшой пример кода? Мне просто любопытно узнать, должна ли проверка типа происходить в том методе, на который вы ссылаетесь, или она должна происходить непосредственно перед тем, как я создам данные страницы. Пожалуйста, простите мое невежество, лол - person mafiOSo; 30.10.2012