5

我正在使用iOS8的今天小部件來顯示與當天相關的信息。問題是,如果沒有相關消息顯示,我不想顯示小部件/部分。如何隱藏iOS 8 Today窗口小部件時什麼都不顯示?

我知道它必須是可能的BA應用程序做它(它只顯示小部件時,有一個航班,其餘時間它根本不可見)。我只是不能找出一種方法來實現這種行爲。

有誰知道這可以做到嗎?

回答

12

我發現這樣做的方法是使用NCWidgetController。這使您可以根據您認爲合適的任何標準輕鬆指定何時顯示當前窗口小部件。

只需添加以下到您的viewDidLoad方法(或任何地方,將被調用時,窗口小部件重新加載)在今天的小工具視圖控制器,它會工作:

BOOL hasDataToDisplay = NO; 

NCWidgetController *widgetController = [NCWidgetController widgetController]; 
[widgetController setHasContent:hasDataToDisplay forWidgetWithBundleIdentifier:@"com.my-company.my-app.my-widget"]; 

蘋果文檔:https://developer.apple.com/library/ios/documentation/NotificationCenter/Reference/NCWidgetController_Class/index.html#//apple_ref/occ/cl/NCWidgetController

警告:一旦您設置了沒有要顯示的內容,則無法從小部件本身重置NCWidgetController。換句話說,一旦您將其設置爲NO,那麼除非您從父/包含應用程序觸發它,否則不會返回。

+0

喜,爲超級答案,但問題tahnks請爲這個注:「NCWidgetController不能從窗口小部件本身復位,一旦你已經設置沒有要顯示的內容。換句話說,一旦你將其設置爲NO,那麼除非你從父/包含應用程序中觸發它,否則不會返回。「我怎麼能」從父母/包含應用程序觸發它「我沒有得到你很好,你能給我例子嗎?非常感謝 – Rawan 2017-10-25 09:45:09

-1

這是更好地利用

+ (instancetype)widgetController 

然後調用

- (void)setHasContent:(BOOL)flag forWidgetWithBundleIdentifier:(NSString *)bundleID 
+0

爲什麼你認爲這樣更好? – defense2000x 2015-02-23 13:49:07

+0

@ defence2000x,因爲這是記錄在https ://developer.apple.com/library/ios/documentation/NotificationCenter/Reference/NCWidgetController_Class/index.html#//apple_ref/occ/clm/NCWidgetController/widgetController – jeeeyul 2015-04-21 06:27:22

3

在widget的視圖控制器的viewDidLoad方法中添加以下內容:

BOOL DisplayWidget = NO; 
[[NCWidgetController widgetController] setHasContent:DisplayWidget 
         forWidgetWithBundleIdentifier:@"<widget's bunder identifier>"]; 

這將顯示禁用窗口小部件。

要再次啓用它,您必須使用同一行傳遞YES給setHasContent參數從包含的應用程序執行此操作。確保必要的進口增加了包含應用程序的視圖控制器將重新啓用該插件:

#import <NotificationCenter/NotificationCenter.h> 

@interface ViewController() <NCWidgetProviding> {...} 

[查看41頁的單證的widget的 https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensibilityPG.pdf]

0

的方法,我使用時,雖然不完美,並在通知中心小余種,但爲我工作:

在viewDidLoad中()首選內容大小的高度設置爲1:

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view from its nib. 
    preferredContentSize = CGSizeMake(0, 1) 
    view.setNeedsLayout() 
} 

那麼當小部件更新,得到真正的高度,並將其設置:

var data: NSData? 

func updateData() { 
    // fetch data 
    if let data = data { 
     let viewHeight: CGFloat 
     // UI preperation and initialize viewHeight var 
     preferredContentSize = CGSizeMake(0, viewHeight); 
    } else { 
     preferredContentSize = CGSizeMake(0, 1); 
    } 

} 

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { 
    // Perform any setup necessary in order to update the view. 

    // If an error is encountered, use NCUpdateResult.Failed 
    // If there's no update required, use NCUpdateResult.NoData 
    // If there's an update, use NCUpdateResult.NewData 

    updateData() 

    completionHandler(data != nil ? NCUpdateResult.NewData : NCUpdateResult.NoData) 
}