簡體   English   中英

在解除Modal Segue后更新UIViewController

[英]Update UIViewController after Dismissing Modal Segue

我目前正在為我的第一款iPhone游戲設計結構並遇到問題。 目前,我有一個'MenuViewController',它允許你選擇要播放的關卡和一個'LevelViewController'來播放關卡。

'MenuViewController'上的UIButton觸發'LevelViewController'的模態segue。

'LevelViewController'上的UIButton觸發以下方法返回'MenuViewController':

-(IBAction)back:(id)sender //complete
{
    [self dismissModalViewControllerAnimated:YES];
}

問題是,我在菜單頁面上有一個UILabel ,用於打印玩家擁有的總點數。 每當我從關卡中返回菜單時,我希望此標簽自動更新。 目前,標簽是在“MenuViewController”中以編程方式定義的:

-(void)viewDidLoad {
    [super viewDidLoad];
    CGRect pointsFrame = CGRectMake(100,45,120,20);
    UILabel *pointsLabel = [[UILabel alloc] initWithFrame:pointsFrame];
    [pointsLabel setText:[NSString stringWithFormat:@"Points: %i", self.playerPoints]];
    [self.pointsLabel setTag:-100]; //pointsLabel tag is -100 for id purposes
}

self.playerPoints是MenuViewController的整數屬性

有沒有辦法可以更新標簽? 提前謝謝!

這是授權的完美案例。 當LevelViewController完成后,它需要觸發一個在MenuViewController中處理的委托方法。 這個委托方法應該關閉模態VC,然后做你需要做的其他事情。 呈現VC通常應該解除它所呈現的模態視圖。

以下是如何實現此目的的基本示例:

LevelViewController.h(接口聲明之上):

@protocol LevelViewControllerDelegate
    -(void)finishedDoingMyThing:(NSString *)labelString;
@end

ivar部分內的相同文件:

__unsafe_unretained id <LevelViewControllerDelegate> _delegate;

ivar部分下面的相同文件:

@property (nonatomic, assign) id <LevelViewControllerDelegate> delegate;

在LevelViewController.m文件中:

@synthesize delegate = _delegate;

現在在MenuViewController.h中, #import "LevelViewController.h"並將自己聲明為LevelViewControllerDelegate的委托:

@interface MenuViewController : UIViewController <LevelViewControllerDelegate>

現在在MenuViewController.m中實現委托方法:

-(void)finishedDoingMyThing:(NSString *)labelString {
    [self dismissModalViewControllerAnimated:YES];
    self.pointsLabel.text = labelString;
}

然后確保在呈現模式VC之前將自己設置為LevelViewController的委托:

lvc.delegate = self;  // Or whatever you have called your instance of LevelViewController

最后,當你完成LevelViewController中你需要做的事情時,只需調用:

[_delegate finishedDoingMyThing:@"MyStringToPassBack"];

如果這沒有意義,我和我可以試着幫助你理解。

創建一個指向UILabel的屬性self.pointsLabel ,然后你可以調用類似[self.pointsLabel setText:[NSString stringWithFormat:@"Points: %i", self.playerPoints]]; 使用新分數更新標簽

在模態視圖頭文件中,添加屬性:

@property (nonatomic,assign) BOOL updated;

然后在主視圖控制器中,使用didViewAppear,例如:

-(void)viewDidAppear:(BOOL)animated{
    if (modalView.updated == YES) {
        // Do stuff
        modalView.updated = NO;
    }
}

其中“modalView”是您可能在那里分配/初始化的UIViewController的名稱。

如果要傳遞更多信息,請添加更多屬性,例如用戶選擇的級別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM