如何在代码中设置UIButton的图像?
我有这个:
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];
但是看不到会为它设置图像的内容.
Objective-C的
UIImage *btnImage = [UIImage imageNamed:@"image.png"]; [btnTwo setImage:btnImage forState:UIControlStateNormal];
斯威夫特4
let btnImage = UIImage(named: "image") btnTwo.setImage(btnImage , for: UIControlState.normal)
Mike的解决方案只显示图像,但按钮上的任何标题都不可见,因为您可以设置标题或图像.
如果要同时设置(图像和标题),请使用以下代码:
btnImage = [UIImage imageNamed:@"image.png"]; [btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal]; [btnTwo setTitle:@"Title" forState:UIControlStateNormal];
在此之前,我必须根据图像帧大小明确调整按钮框的大小.
UIImage *listImage = [UIImage imageNamed:@"list_icon.png"]; UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom]; // get the image size and apply it to the button frame CGRect 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;
在Swift用户的情况下
// case of normal image let image1 = UIImage(named: "your_image_file_name_without_extension")! button1.setImage(image1, forState: UIControlState.Normal) // in case you don't want image to change when "clicked", you can leave code below // case of when button is clicked let image2 = UIImage(named: "image_clicked")! button1.setImage(image2, forState: UIControlState.Highlight)
你可以这样做
[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(0, 0, 150, 44); [btn setBackgroundImage:[UIImage imageNamed:@"buttonimage.png"] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(btnSendComment_pressed:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn];
您可以将图像置于以下任一方式:
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]; [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];