Search code examples
swiftwatchkitapple-watch

Using setBackgroundImageNamed with iteration


In WatchKit, is there a way to assign background images to similarly named groups by using an iterative process such as in the example below? (groupName + i) must be replaced, though I'm not sure with what precisely.

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var groupName0: WKInterfaceGroup!
    @IBOutlet weak var groupName1: WKInterfaceGroup!
    @IBOutlet weak var groupName2: WKInterfaceGroup!

    @IBAction func ButtonPressed() {
        for var i = 0, i < 3, i++ {
            (groupName + i).setBackgroundImageNamed("Image" + String(i))
        }
    }
}

Solution

  • Just add your WKInterfaceGroup instances to an array and iterate over that. Variables aren't strings, so you can't just concatenate a variable name. Also, you shouldn't name your variables xxxName: they are references to object instances, not strings.