ios - How to set image for button in Swift/Xcode -


i receiving "nil" error when trying set image button programmatically. doing wrong? these not optionals.

@iboutlet weak var scrollview: uiscrollview!  var imagebutton: uibutton! var index: int = 0  var images: [uiimage] = [uiimage(named: "image1.png")!, uiimage(named: "image2.png")!, uiimage(named: "image3.png")!, uiimage(named: "image4.png")!, uiimage(named: "image5.png")!, uiimage(named: "image6.png")!, uiimage(named: "image7.png")!, uiimage(named: "image8.png")!, uiimage(named: "image9.png")!, uiimage(named: "image10.png")!, uiimage(named: "image11.png")!, uiimage(named: "image12.png")!, uiimage(named: "image13.png")!, uiimage(named: "image14.png")!, uiimage(named: "image15.png")!, uiimage(named: "image16.png")!, uiimage(named: "image17.png")!, uiimage(named: "image18.png")!, uiimage(named: "image19.png")!, uiimage(named: "image20.png")!, uiimage(named: "image21.png")!, uiimage(named: "image22.png")!, uiimage(named: "image23.png")!, uiimage(named: "image24.png")!, uiimage(named: "image25.png")!, uiimage(named: "image26.png")!, uiimage(named: "image27.png")!, uiimage(named: "image28.png")!, uiimage(named: "image29.png")!, uiimage(named: "image30.png")!]   override func viewdidload() {     super.viewdidload()     // additional setup after loading view, typically nib.      let screensize: cgrect = uiscreen.mainscreen().bounds     let screenwidth = screensize.width     //let screenheight = screensize.height      let numwidth: cgfloat = 3     let numheight: cgfloat = 10     self.scrollview.frame.size.width = screenwidth     let width: cgfloat = (self.scrollview.frame.size.width - (numwidth + 1))/3      var i:cgfloat = 0; < 3; ++i{         var j:cgfloat = 0; j < 10; ++j {              let image: uiimage = images[index] uiimage!               imagebutton.setimage(image,forstate:uicontrolstate.normal)             imagebutton.frame = cgrectmake(width*i, width*j, width, width)             self.scrollview.addsubview(imagebutton)              index++         }     }     scrollview.contentsize.height = (width)*numheight 

i think creating image image again.

just like

imagebutton.setimage(images[index],forstate:uicontrolstate.normal) 

hope work.

or can :

var images = [string]? 

in viewdidload

images = ["image1.png","image2.png"] let img : uiimage = uiimage(named: images[index])! imagebutton = uibutton.buttonwithtype(uibuttontype.system) uibutton button.frame = cgrectmake(100, 100, 100, 100)//set own frame imagebutton.setimage(img,forstate:uicontrolstate.normal) 

and check image must available in project


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -