table 行中的 WKInterfaceSwitch 或 WKInterfaceButton —— 触摸了哪一行?

WKInterfaceSwitch or WKInterfaceButton in a table row -- which row was touched?

我的 Apple Watch 应用程序中有一个 table,其中包含 WKInterfaceSwitch 的行。同排控制器有10排,其中包括一个开关。换句话说,在 table 的 10 个不同行中有 10 个开关,其中每一行都是同一行控制器的实例。

当用户触摸开关并更改其状态时,将调用操作方法,但不会传递对开关的引用,只会传递其新值。与 WKInterfaceButton 类似——与 UIKit 不同,没有传递引用。

那么我如何知道触摸了 10 个开关(或按钮)中的哪一个?

请注意,我无法为每个开关的操作分配不同的选择器,因为它们都在同一个 class 的实例中,即行控制器。

有没有可能只是不可能?

您可以通过向行控制器添加自定义委托来完成此操作class。配置行控制器时,将界面控制器设置为委托。然后,确保在行控制器中处理 switch/button 操作。调用委托并传递您可能已在行控制器中配置的任何其他信息。

这是参考@Mike Swanson 的回答的示例代码

// ListRowController.swift file: 
protocol rowButtonClicked {
    func rowClicked(atIndex:Int)
}

class ListRowController: NSObject {

 @IBOutlet var btnApply: WKInterfaceButton!

    let delegate : rowButtonClicked? = nil
    var rowNumber : Int = 0

  @IBAction func applyTapped()

    {
        print(rowNumber)
        self.delegate?.rowClicked(atIndex: rowNumber)

    }

}


//in class containing table
 dont forget to add delegate: rowButtonClicked 
override func awake(withContext context: Any?)
{
        super.awake(withContext: context)

     listView.setNumberOfRows(customTones.count, withRowType: "availableAlarmList")

        for index in 0..<listView.numberOfRows{
            if let controller = listView.rowController(at: index) as? ListRowController {

                controller.rowNumber = index
                controller.delegate = self
            }
        }
    func rowClicked(atIndex:Int) // delegate method which will give the row index
    {
        // do something here
    }
}