2015-04-25 3 views
0

Я пытаюсь переместить методы из делегата приложения и вместо этого использовать отдельный контроллер представления для соответствия протоколу. Старое приложение делегата:Как перенести методы из делегата приложения?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    self.qnaire = [[VRQuestionnaire alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"set1" 
                         ofType:@"json"]]; 

    self.navController = (UINavigationController *)self.window.rootViewController; 
    [self prepareForQuestion:self.qnaire.firstQuestion animated:NO]; 

    return YES; 
} 

/* Set up the question view controller with a question and push onto the nav stack 
*/ 
- (void)prepareForQuestion:(VRQuestion *)question animated:(BOOL)animated; 
{ 
    VRQuestionViewController *qvc = (VRQuestionViewController *)[self.navController.storyboard instantiateViewControllerWithIdentifier:@"QuestionViewController"]; 
    qvc.delegate = self; 

    qvc.question = question; 
    [self.navController pushViewController:qvc animated:animated]; 
} 

/* Delegate that gets called every time a question is answered. This loads the next question and pushes it onto the nav stack. 
It also pushes a pointer to the question and result to a linked-list called firstAnswer->nextAnswer->nextAnswer, etc. 

When the next question returns nil we know we've finished as there are no more questions and log linked-list to console. 
*/ 
- (void)questionViewController:(VRQuestionViewController *)controller didAnswerQuestion:(VRQuestion *)question withResult:(BOOL)result 
{ 
    VRQuestion *nextQuestion = nil; 

    if (result == YES) { 
     nextQuestion = question.nextYesQuestion; 
    } else if (result == NO) { 
     nextQuestion = question.nextNoQuestion; 
    } 
    [self.qnaire pushAnswerResult:result forQuestion:question]; 

    // Handle no more questions 
    if(nextQuestion) { 
     [self prepareForQuestion:nextQuestion animated:YES]; 

    } else { 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Complete" 
                  message:@"You completed the questionnaire" 
                  delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
     [alertView show]; 
     [self.qnaire logAnswers]; 
    } 
} 

И я пытаюсь перенести эти методы в InitialViewController, но кнопка не делает ничего?

@implementation InitialViewController 
- (IBAction)buttonPress:(UIButton *)sender { 

    self.qnaire = [[VRQuestionnaire alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"set1" 
                         ofType:@"json"]]; 
    //self.navController = (UINavigationController *)self.window.rootViewController; 
    [self prepareForQuestion:self.qnaire.firstQuestion animated:NO]; 

} 

Заранее спасибо.

кнопка

InitialViewController должен вызвать VRQuestionViewController (ниже)

@interface VRQuestionViewController() 

@end 

@implementation VRQuestionViewController 

- (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)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 


    self.label.text = self.question.text; 
    self.title = [self.question.identifier uppercaseString]; 
} 

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

- (IBAction)yesPressed:(id)sender 
{ 
    if (self.delegate != nil) { 
     if ([self.delegate respondsToSelector:@selector(questionViewController:didAnswerQuestion:withResult:)]) { 
      [self.delegate questionViewController:self didAnswerQuestion:self.question withResult:YES]; 
     } 
    } 
} 

- (IBAction)noPressed:(id)sender 
{ 
    if (self.delegate != nil) { 
     if ([self.delegate respondsToSelector:@selector(questionViewController:didAnswerQuestion:withResult:)]) { 
      [self.delegate questionViewController:self didAnswerQuestion:self.question withResult:NO]; 
     } 
    } 
} 

@end 

Мой текущий AppDelegate:

#import <UIKit/UIKit.h> 
#import "VRQuestionnaire.h" 
#import "VRQuestionViewController.h" 

@interface VRAppDelegate : UIResponder <UIApplicationDelegate> 


@property (strong, nonatomic) UIWindow *window; 
@property (strong, nonatomic) VRQuestionnaire *qnaire; 


@end 



#import "VRAppDelegate.h" 
#import "VRQuestionViewController.h" 

@implementation VRAppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 

    self.qnaire = [[VRQuestionnaire alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"set1" 
                         ofType:@"json"]]; 


    return YES; 
} 

И InitialViewController:

#import "VRAppDelegate.h" 
#import "VRQuestionViewController.h" 

@implementation VRAppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 

    self.qnaire = [[VRQuestionnaire alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"set1" 
                         ofType:@"json"]]; 


    return YES; 
} 

#import "InitialViewController.h" 

@interface InitialViewController() 

@end 

@implementation InitialViewController 
- (IBAction)buttonPress:(UIButton *)sender { 

    self.qnaire = [[VRQuestionnaire alloc] initWithFile:[[NSBundle mainBundle] pathForResource:@"set1" 
                         ofType:@"json"]]; 

    self.navController = (UINavigationController *)self.window.rootViewController; 

    [self prepareForQuestion:self.qnaire.firstQuestion animated:NO]; 


} 



/* Set up the question view controller with a question and push onto the nav stack 
*/ 
- (void)prepareForQuestion:(VRQuestion *)question animated:(BOOL)animated; 
{ 
    VRQuestionViewController *qvc = (VRQuestionViewController *)[self.navController.storyboard instantiateViewControllerWithIdentifier:@"QuestionViewController"]; 
    qvc.delegate = self; 

    qvc.question = question; 
    [self.navController pushViewController:qvc animated:animated]; 
} 

/* Delegate that gets called every time a question is answered. This loads the next question and pushes it onto the nav stack. 
It also pushes a pointer to the question and result to a linked-list called firstAnswer->nextAnswer->nextAnswer, etc. 

When the next question returns nil we know we've finished as there are no more questions and log linked-list to console. 
*/ 
- (void)questionViewController:(VRQuestionViewController *)controller didAnswerQuestion:(VRQuestion *)question withResult:(BOOL)result 
{ 
    VRQuestion *nextQuestion = nil; 

    if (result == YES) { 
     nextQuestion = question.nextYesQuestion; 
    } else if (result == NO) { 
     nextQuestion = question.nextNoQuestion; 
    } 
    [self.qnaire pushAnswerResult:result forQuestion:question]; 

    // Handle no more questions 
    if(nextQuestion) { 
     [self prepareForQuestion:nextQuestion animated:YES]; 

    } else { 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Complete" 
                  message:@"You completed the questionnaire" 
                  delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
     [alertView show]; 
     [self.qnaire logAnswers]; 
    } 
} 



- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view from its nib. 
} 

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

/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

@end 

Have CTR L-перетаскивание из навигационного контроллера для создания контроллера корневого контроллера InitialViewController. CTRL-перетаскивается из кнопки в VRQuestionViewController.

В тренажере при нажатии кнопки VRQuestionViewController отображаются без какого-либо вопроса или ответа на Y/N

К сожалению я сделать реальные свинья ухо, если это!

+1

Почему контроллер вида? Это больше похоже на то, что у вас должен быть вопрос или контролер вопросника. Предположительно, ваша текущая проблема заключается в том, что 'self.navController' равен нулю? – Wain

+0

точно self.navController - это нуль .. я застрял! – Hegar20

+0

Является ли 'InitialViewController' контроллером корневого представления в вашем контроллере навигации? – Wain

ответ

0

Код в вопросе, кажется, пример код на Github, перечисленный в https://github.com/rwarrender/DynamicQuestions

Для удобочитаемости совсем немного логики происходит в приложении делегата. Делегат приложения инициализирует экземпляр VRQuestionnaire и задает вопросы. Затем он настраивает первый контроллер вида на контроллере навигации. Каждый VRQuestionViewController настроен так, что делегат приложения также является делегатом VRQuestionViewController. Как только вопрос будет дан ответ, он перезвонит questionViewController:didAnswerQuestion:withResult:, где делегат приложения нажимает результат на список ответов вопросника, а затем перемещается вдоль дерева вопросов, чтобы отобразить следующий вопрос.

Как предложил Wain, если вы хотели бы расширить его до более чем примера, вероятно, вы переместите код удаления приложения в класс контроллера. У вас возникают проблемы с классом контроллера начального класса, потому что все обернуто внутри контроллера навигации, поэтому ваш навигационный контроллер должен быть начальным контроллером представления в раскадровке с классом InitialViewController в качестве контроллера корневого представления контроллера навигации. Вы делаете это путем перетаскивания правого клика с контроллера навигации в раскадровке до InitialViewController.

Надеюсь, что это поможет!

+0

Это помогает, но я все еще не вижу чего-то здесь - обновил свой вопрос – Hegar20

+0

@Wain Я установил InitialViewController в качестве корневого контроллера, как вам и @Electron. Я нахожу qvc return nil, тогда как в исходном коде это экземпляр VRQuestionViewController. '- (void) prepareForQuestion: (VRQuestion *) вопрос анимированный: (BOOL) анимированный; { VRQuestionViewController * qvc = (VRQuestionViewController *) [self.navController.storyboard instantiateViewControllerWithIdentifier: @ "QuestionViewController"]; qvc.delegate = self; qvc.question = вопрос; // qvc nil [self.navController pushViewController: qvc анимированный: анимированный]; } ' – Hegar20