在关闭模态 Segue 后更新 UIViewController



我目前正在为我的第一个iPhone游戏设计结构,遇到了一个问题。目前,我有一个"MenuViewController",允许您选择要玩的关卡和一个"LevelViewController"来播放关卡。

"MenuViewController"上的UIButton触发了"LevelViewController"的模式序列。

"LevelViewController"上的UIButton触发以下方法返回到"MenuViewController":

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

问题是,我在菜单页面上有一个UILabel,可以打印玩家的总积分。每当我从关卡返回菜单时,我都希望此标签自动更新。目前,标签在"菜单视图控制器"中以编程方式定义:

-(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"是您可能在那里分配/初始化的UIView控制器的名称。

如果要传递更多信息(例如用户选择的级别),请添加更多属性。

最新更新