【问题标题】:Define UIabel in appdelegate在 appdelegate 中定义 UIabel
【发布时间】:2013-04-04 18:02:51
【问题描述】:

所以,在这个项目的最后阶段,我决定需要通知。 问题是,我在 MainViewController 中设置了一个 UILabel,它从那里的输入中获取它的值,并且我需要将这些值用于我的通知设置中的时间间隔,当应用程序进入后台时会调用该时间间隔。 (代码位于Appdelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSDate *alertTime = [[NSDate date]
                     dateByAddingTimeInterval:[self.labelone.text intValue] * 60];
UIApplication* app = [UIApplication sharedApplication];
UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
                                    init];
if (notifyAlarm)
{
    notifyAlarm.fireDate = alertTime;
    notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    notifyAlarm.repeatInterval = 0;
    notifyAlarm.soundName = UILocalNotificationDefaultSoundName;
    notifyAlarm.alertBody = @"Staff meeting in 30 minutes";
    [app scheduleLocalNotification:notifyAlarm];
    }
}

我已尝试普遍添加UILabel (self.labelone),但无论我尝试什么,它都会引发错误。任何帮助或提示将不胜感激!

【问题讨论】:

  • 您的labelone 位于MainViewController 中,因此您无法通过self..... 中的Appdelegate 访问它。
  • 我是这么想的,但我该怎么办? labelone 根本无法识别。

标签: ios objective-c xcode


【解决方案1】:

您可以在 MainViewController 的 viewDidLoad 方法中通过 NSNotificationCenter 注册通知来监听 MainViewController 中的后台通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

当应用进入后台时,您的 MainViewController 将调用选择器 willEnterBackground:,因此您需要进行设置:

- (void)willEnterBackground:(NSNotification *)notification {
    ...you can now access self.labelone
}

在 MainViewController viewDidUnload 方法中,移除该通知的观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

【讨论】:

  • 我现在要试试这个,感谢您的提醒。我无法为NSNotificationCenter 找到任何好的资源。
  • 所以基本上只要稍微调整一下,这应该可以完美运行,这意味着我不会阻塞我的代表。感谢NSNotification@daltonclaybrook 的速成课程!
【解决方案2】:

在您的AppDelegate 中,创建一个名为timeIntervalLabelUILabel 弱属性。

然后在MainViewControllerviewDidLoad 内简单地做:

AppDelegate *d = [UIApplication sharedApplication].delegate;
d.timeIntervalLabel = self.labelone

最后,在您的applicationDidEnterBackground 中,您可以使用self.timeIntervalLabel

【讨论】:

  • 根据 MVC 标准,从您的 App Delegate 访问 UI 元素并不是一种好的做法,这被视为模型的一部分。这应该仅由 View Controller 处理。
  • 谢谢你,我从来没有在任何地方看到过这么简单的解释。只是想知道,它仍然会引发未定义标签一的错误。如果我定义它,它是否仍会在 AppDelegate 上更新,还是会开始自行行动?编辑:我将属性添加回视图控制器,它按预期工作
  • 谢谢道尔顿。我知道这一点,但我不知道另一种方式,并认为只有一个标签不会受到伤害:)
  • 是的,显然标签在很多方面都是错误的,但我试图用最小的改变来解决他的具体问题。通过 UI 组件管理特定于应用程序的信息确实是完全错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2012-11-17
  • 2014-06-16
相关资源
最近更新 更多