Swift观察UIApplication属性

时间:2016-04-05 09:15:17

标签: ios swift key-value-observing uiapplicationdelegate uiapplication

是否有可能以某种方式观察UIApplication.sharedApplication()中的swift的属性?

我需要跟踪UIApplication.sharedApplication().applicationIconBadgeNumber根据该号码更新我的应用UI,但每当此属性更改时,UI都不会受到影响。

我的相关代码:

private var badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.notificationsButton.setTitle(self.badgeCount, forState: .Normal)
}

2 个答案:

答案 0 :(得分:2)

这个解决方案可能适用于您通过扩展将iconBadgeNumber计算变量添加到UIApplication,它将设置真实变量并通知您的应用程序更改

extension UIApplication
{
  var iconBadgeNumber:Int { set{self.applicationIconBadgeNumber = iconBadgeNumber
            NSNotificationCenter.defaultCenter().postNotificationName("BageNumberChanged", object: nil)
        } get{return self.applicationIconBadgeNumber}}
}

//Add this at Observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(Controller.Method), name: "BageNumberChanged", object: nil)

答案 1 :(得分:0)

enter image description here

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.


     UIApplication.sharedApplication().applicationIconBadgeNumber = 5

    return true
}
 override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)

        let badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

        let notificationsButton: UIButton = UIButton (type: UIButtonType.Custom)

        notificationsButton.addTarget(self, action: "tapBarNotificationsButton", forControlEvents: UIControlEvents.TouchUpInside)

        notificationsButton.frame = CGRectMake(0, 0, 25, 25)

        notificationsButton.backgroundColor = UIColor.blackColor()

        notificationsButton.setTitle(badgeCount, forState: .Normal)

        let barnotificationsButton = UIBarButtonItem(customView: notificationsButton)

        self.navigationItem.setRightBarButtonItem(barnotificationsButton, animated: true)



    }
相关问题