Here's some code I grabbed from uibutton-in-code
btnImage = [UIImage imageNamed:@"image.png"]; [btnTwo setImage:btnImage forState:UIControlStateNormal];
In ruby, and with my own needs and wants and desires:
ok_up_image = UIImage.imageNamed 'ok_up.png' ok_down_image = UIImage.imageNamed 'ok_down.png' @button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @button.frame = [[0, 0], [51, 34]] @button.setImage(ok_up_image, forState:UIControlStateNormal) @button.setImage(ok_down_image, forState:UIControlStateHighlighted)
Here is another good reference, btw: learn-programming
Here are the images:
Let's see what this code does when I add it to my basic skeleton:
def viewDidLoad ok_up_image = UIImage.imageNamed 'ok_up.png' ok_down_image = UIImage.imageNamed 'ok_down.png' @button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @button.frame = [[134, 223], [51, 34]] @button.setImage(ok_up_image, forState:UIControlStateNormal) @button.setImage(ok_down_image, forState:UIControlStateHighlighted) view.addSubview(@button) end
It ran on the first try - that never happens! So that was cool... here are screenshots. A neat feature is that in the simulator, a blue line appears when pressing the button.
Wait, what!? wtf. Man, sometimes I think Cocoa/CocoaTouch is just full of bugs, and Apple tricks us into thinking it's our fault. What could be wrong here!?
Fixthit!
The problem with the background is in my choice of "type":
# WRONG! @ok_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) # FIXED! @ok_button = UIButton.buttonWithType(UIButtonTypeCustom)
more buttons
def viewDidLoad images = { ok: { up: UIImage.imageNamed('ok_up.png'), down: UIImage.imageNamed('ok_down.png'), }, plus: { up: UIImage.imageNamed('plus_up.png'), down: UIImage.imageNamed('plus_down.png'), }, minus: { up: UIImage.imageNamed('minus_up.png'), down: UIImage.imageNamed('minus_down.png'), }, } @minus_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @minus_button.frame = [[134 - 51, 223], [51, 43]] @minus_button.setImage(images[:minus][:up], forState:UIControlStateNormal) @minus_button.setImage(images[:minus][:down], forState:UIControlStateHighlighted) @plus_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @plus_button.frame = [[134, 223], [51, 43]] @plus_button.setImage(images[:plus][:up], forState:UIControlStateNormal) @plus_button.setImage(images[:plus][:down], forState:UIControlStateHighlighted) @ok_button = UIButton.buttonWithType(UIButtonTypeRoundedRect) @ok_button.frame = [[134 + 51, 223], [51, 34]] @ok_button.setImage(images[:ok][:up], forState:UIControlStateNormal) @ok_button.setImage(images[:ok][:down], forState:UIControlStateHighlighted) view.backgroundColor = UIColor.grayColor view.addSubview(@plus_button) view.addSubview(@minus_button) view.addSubview(@ok_button) end
