>圖片1(建立今日擴展)swift
>圖片2api
>圖片3(設置大小)app
>圖片4(繪畫控件)ide
>圖片5(設置共享文件)ui
>圖片6(設置羣組ID)url
>圖片7(設置URL Schemes)spa
>擴展中的主要邏輯代碼3d
class TodayViewController: UIViewController, NCWidgetProviding,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var newsList = [NewsModel]() lazy var moreBtn:UIButton = { let btn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44)) btn.setTitle("查看更多", for:.normal) btn.addTarget(self, action: #selector(gotoMainApp), for: .touchUpInside) btn.backgroundColor = UIColor(red:245/255.0, green:74/255.0, blue:48/255.0, alpha: 1) return btn }() func gotoMainApp(){ //跳轉到主程序的代碼(見圖7) self.extensionContext?.open(URL(string:"WidgetApp://action=GotoNewsListPage")!, completionHandler: { (suc:Bool) in }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) updateView() } //刷新界面 func updateView(){ if newsList.count != 0{ newsList.removeAll() } //經過UserDefaults從組裏面獲取共享數據(見圖6) let ud = UserDefaults(suiteName: "group.centaHouse"); if let nickName = ud?.array(forKey: "group.centaHouse.centaToday"){ for (_,element) in nickName.enumerated() { if let edic = element as? [String : Any]{ let nm = NewsModel() nm.setValuesForKeys(edic) newsList.append(nm) } } self.tableView.reloadData() if newsList.count != 0 { self.tableView.tableFooterView = self.moreBtn } //判斷在不一樣數據下展現界面的視圖大小(不處理的話,展開和摺疊會出問題) if #available(iOSApplicationExtension 10.0, *) { if extensionContext?.widgetActiveDisplayMode == .compact{ //壓縮狀態 // if newsList.count != 0 { // UIView.animate(withDuration: 0.1, animations: { // self.preferredContentSize = CGSize(width: self.view.bounds.width, height: CGFloat(self.newsList.count*100 + 44)) // }) // } }else{//展開狀態 if newsList.count != 0 { UIView.animate(withDuration: 0.1, animations: { self.preferredContentSize = CGSize(width: self.view.bounds.width, height: CGFloat(self.newsList.count*100 + 44)) }) } } } else { // Fallback on earlier versions } } } override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self //註冊自定義cell let nib = UINib(nibName: "NewsInfoCell", bundle: nil) self.tableView.register(nib, forCellReuseIdentifier: "NewsInfoCell") //設置今日擴展模式爲可張開收縮模式(IOS10之後支持,進入擴展右上角顯示"展開"和"摺疊") if #available(iOSApplicationExtension 10.0, *) { self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded } else { // Fallback on earlier versions }; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //新聞列表 let cell = tableView.dequeueReusableCell(withIdentifier: "NewsInfoCell") as! NewsInfoCell cell.news = newsList[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let url = newsList[indexPath.row].ShowNewsUrl extensionContext?.open(URL(string:"WidgetApp://action=Goto-\(url)")!, completionHandler: { (suc:Bool) in }) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 95; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //監聽擴展的展開和收縮狀態處理視圖的大小 /** * @maxSize 界面可以顯示的最小和最大尺寸(最小狀態下是110) * @activeDisplayMode: 張開和收縮狀態 **/ @available(iOSApplicationExtension 10.0, *) func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if(activeDisplayMode == .compact){ self.preferredContentSize = CGSize(width: maxSize.width, height: maxSize.height) }else{ self.preferredContentSize = CGSize(width: maxSize.width, height: CGFloat(newsList.count*100 + 44)) } } //自行看官方註釋 func widgetPerformUpdate(completionHandler: (@escaping (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 if #available(iOSApplicationExtension 10.0, *) { if extensionContext?.widgetActiveDisplayMode == .compact{ completionHandler(NCUpdateResult.newData) }else{ completionHandler(NCUpdateResult.noData) } } else { // Fallback on earlier versions completionHandler(NCUpdateResult.newData) } } }
#pragma mark app跳轉 (今日通知欄) -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{ NSString* prefix = @"WidgetApp://action="; if ([[url absoluteString] rangeOfString:prefix].location != NSNotFound) { NSString* action = [[url absoluteString] substringFromIndex:prefix.length]; if ([action isEqualToString:@"Goto-"]) { ...... }else{ ...... } } return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; }
//在主程序保存須要展現的數據 func extentionUpdate(){ //group.cenXXX 組名 if let user = UserDefaults(suiteName: "group.cenXXX") { //擴展標識符 user.set(objArray, forKey: "group.cenXXX.cenToday") } }
>收縮狀態orm
>展開狀態blog