iOS:在不同的视图上使用NSUserDefault数据更新文本标签 [英] iOS: Updating text labels with NSUserDefault data on different views

查看:90
本文介绍了iOS:在不同的视图上使用NSUserDefault数据更新文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在视图1上有一个文本标签和一个按钮.如果单击该按钮,则会通过模态连接进入视图2.在此视图中,我输入一个数字并按下一个按钮.该按钮会将数字保存到NSUserDefaults,并尝试更新视图1上的文本标签以反映该数字.

I have a text label on view 1 and a button. If I click the button, I am brought to view 2 through a modal connection. In this view, I enter a number and press a button. The button saves the number to NSUserDefaults, as well as tries to update the text label on view 1 to reflect this number.

按钮的代码:

- (IBAction)returnToView1:(UIButton *)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
defaults setObject:@"myNumber" forKey:@"myKey"];
[defaults synchronize];
_myLabel.text = [defaults stringForKey:@"myKey"];
}

但是,当我返回使用模态连接的视图1时,标签从未更新.我可以通过添加以下代码来解决此问题:

However, when I go back to view 1 using a modal connection, the label never updated. I could solve this by adding the following code:

-(void)viewDidAppear:(BOOL)animated
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_myLabel.text = [defaults stringForKey:@"myKey"];
}

问题是,首先加载视图1,然后填充文本字段,所以它看起来不专业.我希望在加载视图之前填充文本标签.我试过将这段代码放在此方法中:

The problem is, view 1 first loads, and then the text field populates, so it looks unprofessional. I want the text label to populate before loading the view. I've tried placing this code inside of this method:

(void)viewWillAppear:(BOOL)animated

...但是那也不起作用(由于某些原因,文本字段只会在我关闭应用程序,切换到视图2,再次按下按钮然后返回到视图1之后填充.).感谢您的任何建议!

...but that didn't work either (for some reason the text field would only populate after I closed the app, switched to view 2, pressed the button a second time, and then returned to view 1). Thanks for any suggestions!

推荐答案

但是,当我使用模式连接返回视图1时,标签从未更新

However, when I go back to view 1 using a modal connection, the label never updated

可能有两个原因.

  1. 您这样说:

  1. You say this:

_myLabel.text = [defaults stringForKey:@"myKey"];

好吧,也许_myLabel并没有指向视图1中的标签.

Well, maybe _myLabel does not point to the label back in view 1.

单词使用模态连接返回视图1".我希望这并不意味着您正在使用segue.如果是这种情况,那么您做的是非常错误的事情.您正在制作第一个视图控制器的新的,不同的副本.因此,现在您拥有第一个视图控制器的两个副本,并且在第一个视图控制器中更改了标签,但是在其顶部显示了第二个.

The words "go back to view 1 using a modal connection". I hope this does not mean you are using a segue. If that is the case, you are doing a very wrong thing. You are making a new, different copy of the first view controller. So now you have two copies of the first view controller, and you changed the label in the first one but you are showing the second one on top of it.

从模态搜索中恢复的方法不是使用其他模态搜索,而是调用dismissViewControllerAnimated:.

The way you get back from a modal segue is not to use another modal segue, but to call dismissViewControllerAnimated:.

这篇关于iOS:在不同的视图上使用NSUserDefault数据更新文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆