IOS 中什么是 WatchKit?如何使用?代码举例讲解

WatchKit 是苹果提供的 Apple Watch 开发框架。我们可以使用它来开发 Watch App 和 Watch Extension。

使用 WatchKit 的基本步骤:

  1. 在 Xcode 中创建一个 Watch App,它将同时创建一个 WatchKit App 和 WatchKit Extension 目标。
  2. WatchKit App:包含 Watch App 的 Storyboard 和资源文件。
  3. WatchKit Extension:包含逻辑代码和与 IOS 扩展的通信。
  4. 在 Storyboard 中拖拽界面控件来设计 Watch App 的界面。
  5. 创建 WKInterfaceController 类来管理每个界面。
  6. 使用 WKInterfaceButton、WKInterfaceLabel 等组件来显示内容和接收交互。
  7. 通过 WKExtensionDelegate 的消息来与 IOS App 通信。
  8. 在 IOS App 的 AppDelegate 中设置要与 Watch App 通信的 WatchKit Extension:
swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let context = WKExtension.shared().contextForHostingController()
    context.delegate = self
    return true
}
  1. 实现接口 WKExtensionDelegate 与 Watch App 交互。
    下面是一个简单示例:
    InterfaceController.swift:
swift
import WatchKit
import Foundation 

class InterfaceController: WKInterfaceController {
    @IBOutlet var label: WKInterfaceLabel!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        let value = "Hello from WatchKit!"
        label.setText(value)
    }
}