Search code examples
xcodeswiftnsarray

Applying image to random object


I've created an NSArray with buttons and now I wish to apply an image to a randomly chosen button from that array;

let buttons:NSArray = [button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12]
    let range: UInt32 = UInt32(buttons.count)
    let randomNumber = Int(arc4random_uniform(range))
    let buttonstring = buttons.objectAtIndex(randomNumber)

    buttonstring.image() = UIImage(named: "code2")

This last piece of code is where I wish to apply the image to the randomly chosen button. But it has an error saying;

Cannot assign to value: function call returns immutable value


Solution

  • If buttonstring is a UIButton, you have to use something like this:

    buttonstring.setImage(UIImage(named: "code2"), forState: .Normal)
    

    Hope this helps.