Search code examples
macoscocoaswiftnsimageviewxcode6.1

Swift cocoa Osx application imageviews


I am currently working on a swift cocoa osx project. In my project I have 31 NSimageViews named space0, space1, space2, through space30. Each image view has 3 possible images, a green image, a blue image, and a white image. What would be the most efficient way to assign an image to a particular imageview based off of a variable without writing out every possible scenario. For Example if variable x = 10 i want to assign space10 an image and if variable y = 20 assign space20 an image. Thanks


Solution

  • func imgSpace(imgNumber:Int) -> NSImage? {
        if imgNumber ==  0 {return space00.image!}
        if imgNumber ==  1 {return space01.image!}
        if imgNumber ==  2 {return space02.image!}
        if imgNumber ==  3 {return space03.image!}
        if imgNumber ==  4 {return space04.image!}
        if imgNumber ==  5 {return space05.image!}
        if imgNumber ==  6 {return space06.image!}
        if imgNumber ==  7 {return space07.image!}
        if imgNumber ==  8 {return space08.image!}
        if imgNumber ==  9 {return space09.image!}
        if imgNumber ==  10 {return space10.image!}
        if imgNumber ==  11 {return space11.image!}
        if imgNumber ==  12 {return space12.image!}
        if imgNumber ==  13 {return space13.image!}
        if imgNumber ==  14 {return space14.image!}
        if imgNumber ==  15 {return space15.image!}
        if imgNumber ==  16 {return space16.image!}
        if imgNumber ==  17 {return space17.image!}
        if imgNumber ==  18 {return space18.image!}
        if imgNumber ==  19 {return space19.image!}
        if imgNumber ==  20 {return space20.image!}
        if imgNumber ==  21 {return space21.image!}
        if imgNumber ==  22 {return space22.image!}
        if imgNumber ==  23 {return space23.image!}
        if imgNumber ==  24 {return space24.image!}
        if imgNumber ==  25 {return space25.image!}
        if imgNumber ==  26 {return space26.image!}
        if imgNumber ==  27 {return space27.image!}
        if imgNumber ==  28 {return space28.image!}
        if imgNumber ==  29 {return space29.image!}
        if imgNumber ==  30 {return space30.image!}
        return nil
    }
    let x = 3
    if let myImage = imgSpace(x) {
        yourOutleT.image = myImage
    }
    let y = 13
    if let myImage = imgSpace(y) {
        yourOutleT.image = myImage
    }
    let z = 27
    if let myImage = imgSpace(z) {
        yourOutleT.image = myImage
    }