• Swift3 今日(TodayExtension)扩展图文笔记


    >图片1(创建今日扩展)

          

    >图片2

     >图片3(设置大小)

     >图片4(绘画控件)

     >图片5(设置共享文件)

     >图片6(设置群组ID)

    >图片7(设置URL Schemes)

     >扩展中的主要逻辑代码

    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,  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( 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( 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( maxSize.width, height: maxSize.height)
            }else{
                self.preferredContentSize = CGSize( 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")
            }
        }
    

     >收缩状态

    >展开状态

      

      

      

  • 相关阅读:
    删DS.Store
    switch 多重选择
    PrintWrite写入文件
    读取文件
    notepad++如何把文件保存为java文件
    让notepad++成为轻量级JAVA的IDE
    Jenkins构建Python项目提示:'python' 不是内部或外部命令,也不是可运行的程序
    相关服务账号
    Jenkins安装与启动
    jmeter安装
  • 原文地址:https://www.cnblogs.com/mapanguan/p/6520572.html
Copyright © 2020-2023  润新知