美文网首页
swift 今日插件(TodayExtension)

swift 今日插件(TodayExtension)

作者: mapg | 来源:发表于2017-03-24 16:44 被阅读124次

图片1(创建今日扩展)

图片2

图片3(设置大小)

图片4(绘画控件)

图片5(设置共享文件)

图片6(设置群组ID)

图片7(设置URL Schemes)

扩展中的主要逻辑代码

import UIKit

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)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        //注册自定义cell
        let nib = UINib(nibName: "NewsInfoCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "NewsInfoCell")
        updateView()
    }
    
    //刷新界面
    func updateView(){
        if newsList.count != 0{
            newsList.removeAll()
        }
        //通过UserDefaults从组里面获取共享数据(见图6)
        let ud = UserDefaults(suiteName: "group.xxx");
       //if let nickName = ud?.array(forKey: "group.xxx.XXX"){
           // 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{ //压缩状态
                 //
                }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()
        //设置今日扩展模式为可张开收缩模式(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)
        }
    }
}

收缩状态



展开状态


相关文章

网友评论

      本文标题:swift 今日插件(TodayExtension)

      本文链接:https://www.haomeiwen.com/subject/oeyfottx.html