How do you set the image for a UIButton in code?
I have this:
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTwo];
but don't see what will set the image for it.
Any help appreciated, Thanks // :)
Try something like:
ReplyDeletebtnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];
Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.
ReplyDeleteIf you want to set both (your image and title) use the following code:
btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];
You can put the image in either of the way:
ReplyDeleteUIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];
//OR setting as background image
[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];
[self.view addSubview:btnTwo];