Reputation: 47
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?
Upvotes: 2
Views: 1160
Reputation: 638
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
}
}
Upvotes: 4
Reputation: 3347
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.
Upvotes: 5