【问题标题】:Swift observe UIApplication propertySwift 观察 UIApplication 属性
【发布时间】:2016-04-05 09:15:16
【问题描述】:
是否有可能以某种方式观察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)
}
【问题讨论】:
标签:
ios
swift
key-value-observing
uiapplicationdelegate
uiapplication
【解决方案1】:
此解决方案可能适用于您通过扩展将 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)
【解决方案2】:
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)
}