• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

>图片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, 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")
        }
    }

 >收缩状态

>展开状态

  

 

 

  

  

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift 5 将进一步减小 iOS 应用安装包大小发布时间:2022-07-13
下一篇:
Swift是开源的发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap