Setting an image for a UIButton in code Setting an image for a UIButton in code ios ios

Setting an image for a UIButton in code


Objective-C

UIImage *btnImage = [UIImage imageNamed:@"image.png"];[btnTwo setImage:btnImage forState:UIControlStateNormal];

Swift 5.1

let btnImage = UIImage(named: "image")btnTwo.setImage(btnImage , for: .normal)


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.

If 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];


Before this would work for me I had to resize the button frame explicitly based on the image frame size.

UIImage *listImage = [UIImage imageNamed:@"list_icon.png"];UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];// get the image size and apply it to the button frameCGRect listButtonFrame = listButton.frame;listButtonFrame.size = listImage.size;listButton.frame = listButtonFrame;[listButton setImage:listImage forState:UIControlStateNormal];[listButton addTarget:self.navigationController.parentViewController                action:@selector(revealToggle:)      forControlEvents:UIControlEventTouchUpInside];UIBarButtonItem *jobsButton =   [[UIBarButtonItem alloc] initWithCustomView:listButton];self.navigationItem.leftBarButtonItem = jobsButton;