是否有可能以某种方式观察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)
}
答案 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)
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)
}