Swift 观察 UIApplication 属性
Posted
技术标签:
【中文标题】Swift 观察 UIApplication 属性【英文标题】:Swift observe UIApplication property 【发布时间】: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)
【问题讨论】:
【参考方案1】:此解决方案可能适用于您通过扩展将 iconBadgeNumber 计算变量添加到 UIApplication,它将设置真实变量并通知您的应用程序更改
extension UIApplication
var iconBadgeNumber:Int setself.applicationIconBadgeNumber = iconBadgeNumber
NSNotificationCenter.defaultCenter().postNotificationName("BageNumberChanged", object: nil)
getreturn 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)
【讨论】:
以上是关于Swift 观察 UIApplication 属性的主要内容,如果未能解决你的问题,请参考以下文章