1. widget的认识
- widget不支持键盘的输入
- 官方文档 App Extension Programming Guide
- 默认左右有一个8的间距
- 默认高度110
- 不支持scrollView
2. 简单使用
-
创建
image.png
-
默认创建出来的是用StoryBoard布局,如果不想用可以删除StoryBoard,并且需要在info.plist文件中进行配置:
image.png -
注意在swift中必须$(PRODUCT_NAME).未前缀,跟swift的命名空间有关,不然找不到该文件,程序会崩溃
3. 创建UI
- 可以viewDidLoad中添加想要展示的View
- 在viewWillAppear中设置可以折叠和展开
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)
}
}
- 点击view打开APP
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
- 主程序中监听打开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
网友评论