我在Swift中尝试Apple Watch开发时遇到了相当基本的任务问题。我最近收到的似乎是Obj C中问题的完美答案,但我似乎无法翻译它。
我有一个接口控制器,它包含一个包含同一行控制器的多行的表。每行包含两个按钮。当点击按钮时,它的背景图像发生了变化,但是需要在接口控制器类中调用另一个函数,并且该函数需要访问接口控制器类中的类级变量。
表连接到接口控制器。按钮连接到行控制器类。这是我简化的Swift代码。谢谢你看看!
/// MY INTERFACE CLASS ///
class MainBoard: WKInterfaceController {
@IBOutlet weak var TileGrid: WKInterfaceTable!
let numRows = 3
let imageNames = ["img1","img2","img3"]
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
initBoard()
}
func initBoard() {
self.TileGrid.setNumberOfRows(self.numRows, withRowType: "Row")
for var i = 0; i < numRows; i++ {
let tmpImageA = UIImage(named: imageNames[0])
let tmpImageB = UIImage(named: imageNames[1])
let rowOfTiles = self.TileGrid.rowControllerAtIndex(i) as Row
rowOfTiles.backImageA = tmpImageA
rowOfTiles.backImageB = tmpImageB
}
}
func doSomething() {
//this function needs to be called whenever a button is pressed
}
}
///////MY ROW CONTROLLER CLASS ////////////////////////
class Row : NSObject {
// At runtime these will be assigned based on the random game board creation
var backImageA = UIImage(named: "default.png")
var backImageB = UIImage(named: "default.png")
@IBOutlet weak var TileA: WKInterfaceButton!
@IBOutlet weak var TileB: WKInterfaceButton!
@IBAction func TapTileA() {
TileA.setBackgroundImage(backImageA)
//NEED TO CALL FUNCTION DO SOMETHING IN INTERFACE CONTROLLER
}
@IBAction func TapTileB() {
TileB.setBackgroundImage(backImageB)
//NEED TO CALL FUNCTION DO SOMETHING IN INTERFACE CONTROLLER
}
}
答案 0 :(得分:2)
我最好的答案是在RowController
课程中创建代理人,然后在InterfaceController
代表可以使用方法buttonOneClickHappened
和buttonTwoClickHappened
然后每个RowController都将委托作为属性,当您创建RowControllers时,调用setDelegate: self
,其中self
是您的InterfaceController
希望这有帮助。