ios - 关闭 Modal Segue 后更新 UIViewController

标签 ios xcode uiviewcontroller uilabel modalviewcontroller

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

“MenuViewController”上的 UIButton 会触发到“LevelViewController”的模式转场。

'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 中处理的委托(delegate)方法。这个委托(delegate)方法应该关闭模式 VC,然后做任何你需要它做的事情。呈现的 VC 通常应处理其呈现的模态视图的驳回。

这是一个如何实现这个的基本示例:

LevelViewController.h(在接口(interface)声明之上):

@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 的委托(delegate):

@interface MenuViewController : UIViewController <LevelViewControllerDelegate>

现在在 MenuViewController.m 中实现委托(delegate)方法:

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

然后确保在呈现模态 VC 之前将自己设置为 LevelViewController 的委托(delegate):

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

最后,当你完成了你需要在 LevelViewController 中做的事情时,只需调用这个:

[_delegate finishedDoingMyThing:@"MyStringToPassBack"];

如果这没有意义,请大声疾呼,我可以尝试帮助您理解。

关于ios - 关闭 Modal Segue 后更新 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11976881/

相关文章:

IOS wkwebview响应式设计不填满全屏

ios - 在 iOS 上带有指示导航栏的侧边栏菜单

iphone - 获取TMXTiledMap的tileet文件名

ios - uiimagepickercontroller调用时,状态栏会返回

ios - 我的 iOS 8 框架是否需要自己的代码签名才能分发?

iOS标签栏 Controller 在 Controller 顶部添加导航按钮

iphone - View 交换技术

iphone - 关于窗口层次结构的警告

swift - 警告 : Attempt to present ViewController on ViewController which is already presenting ViewController

ios - 不阻止访问父级的模态视图