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

你。 提交于 2019-12-11 02:06:11

问题


I have a table in my Apple Watch app with rows that include a WKInterfaceSwitch. There are 10 rows of the same row controller, which includes a switch. In other words, there are 10 switches in 10 different rows of a table where each row is an instance of the same row controller.

When a user touches a switch and changes its state, the action method is called, but a reference to the switch is not passed, only its new value. Similarly for WKInterfaceButton -- unlike UIKit, no reference is passed.

So how do I know which of the 10 switches (or buttons) was touched?

Understand that I cannot assign a different selector for the action of each switch because they are all in instances of the same class, namely the row controller.

Is it possible that it is just not possible?


回答1:


You can accomplish this by adding a custom delegate to your row controller class. When you configure the row controller, set your interface controller as the delegate. Then, make sure you handle your switch/button action in the row controller. Call the delegate and pass along whatever other information you may have configured in your row controller.




回答2:


Here is sample code reffering @Mike Swanson's answer

// 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
    }
}


来源:https://stackoverflow.com/questions/29735301/wkinterfaceswitch-or-wkinterfacebutton-in-a-table-row-which-row-was-touched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!