iOS开发知识小集

Swift中Widget简单使用

2019-03-12  本文已影响78人  向日葵的夏天_summer

1. widget的认识

2. 简单使用

image.png

3. 创建UI

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        extensionContext?.widgetLargestAvailableDisplayMode = .expanded
    }

并在以下方法中设置折叠和展开的高度

func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        if activeDisplayMode == .expanded {
            preferredContentSize = CGSize(width: view.bounds.size.width, height: 160)
        } else {
            preferredContentSize = CGSize(width: view.bounds.size.width, height: 100)
        }
    }
override func viewDidLoad() {
        super.viewDidLoad()
        
        self.preferredContentSize = CGSize(width: view.bounds.size.width, height: 100)

        let margin: CGFloat = 10
        let col: CGFloat = 5
        let itemW: CGFloat = (view.bounds.size.width - margin * (col + 1) - 16) / col
        let itemH: CGFloat = 100
        var itemX: CGFloat = 0
        
        for i in 0..<Int(col) {
            itemX = (itemW + margin) * CGFloat(i) + margin
            let btn = UIButton(frame: CGRect(x: itemX, y: 0, width: itemW, height: itemH))
            btn.backgroundColor = i % 2 == 0 ? .red : .green
            btn.tag = i + 100
            btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
            view.addSubview(btn)
        }
        
        let label = UILabel(frame: CGRect(x: margin, y: 110, width: view.bounds.size.width - margin * 2 - 16, height: 50))
        label.text = "你今天很漂亮,很美丽,今天天气也非常不错!做最好的自己,加油加油!"
        label.textAlignment = .left
        label.textColor = .black
        label.numberOfLines = 2
        label.font = UIFont.systemFont(ofSize: 16)
        view.addSubview(label)
    }
    
    @objc func btnAction(btn: UIButton) {
        if let url = URL(string: "widgettest://id=\(btn.tag)") {
            extensionContext?.open(url, completionHandler: { (finished) in
                print("回调完成的\(finished)---url:\(url)")
            })
        }
    }

首先需要在主APP中配置UrlScheme,


image.png

然后,点击button的时候调用这个url,就能够打开app

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let urlStr = url.absoluteString
        if urlStr.hasPrefix("widgettest") {
            let range = (urlStr as NSString).range(of: "id=")
            let id = (urlStr as NSString).substring(from: range.location + 3)
            print("id====== \(id)")
            return true
        }
        return false

4. 在Widget中使用主程序的Pod文件,这样就可以使用主程序中Podfile里面的文件

image.png
上一篇下一篇

猜你喜欢

热点阅读