Search code examples
swiftuibuttonuiimageios8ios8-extension

Swift: Can't set UIButton image programmatically with error: 'NSString' not a subtype of 'UIImage'


I am trying to set a button image programmatically, and no one seems to have problems with this but me.

My Code:

func moreOptionsKeyMap(){
    for x in self.mainView.subviews as [UIButton]
    {
        let image = UIImage(named: "\(numberImages[0])") as UIImage
        if x.tag == 0 {
            x.setImage(UIImage (named: image), forState: .Normal)
        }

    }
}

I tried directly plugging in the name of the image (This is the line throwing the error)

x.setImage(UIImage (named: "1Key.png"), forState: .Normal)

but I keep getting the same error.

I found an answer on Stackoverflow that said the solution is:

let image = UIImage(named: "name") as UIImage
let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.setImage(image, forState: .Normal)

and everyone says that works fine, so I can't imagine what is wrong with mine.

I'm making a keyboard, so I have buttons set up in Interface Builder, and then in my viewDidLoad

for v in self.mainView.subviews as [UIButton]
    {
        v.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
    }

then in the buttonPressed method I have a switch that calls moreOptionsKeyMap()


Solution

  • At a first glance I would say that here:

    x.setImage(UIImage (named: image), forState: .Normal)
    

    you are passing image, which is a UIImage, whereas a string is expected.

    I think you have to turn this line:

    let image = UIImage(named: "\(numberImages[0])") as UIImage
    

    into:

    let image = "\(numberImages[0])"
    

    So this is how your method should look like:

    func moreOptionsKeyMap() {
        for x in self.mainView.subviews as [UIButton]
        {
            let image = "\(numberImages[0])"
            if x.tag == 0 {
                x.setImage(UIImage (named: image), forState: .Normal)
            }
        }
    }