如何在Swift中更改UIButton图像

我正在尝试使用Swift来更改UIButton的图像…我该怎么做

这是OBJ-C code.but我不知道与斯威夫特:

[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal]; 

从你的Obc-C代码,我想你想设置一个图像的button,所以试试这种方式:

 let playButton = UIButton(type: .Custom) if let image = UIImage(named: "play.png") { playButton.setImage(image, forState: .Normal) } 

简而言之:

 playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal) 

对于Swift 3:

 let playButton = UIButton(type: .custom) playButton.setImage(UIImage(named: "play.png"), for: .normal) 

假设这是你连接的UIButton Name

 @IBOutlet var btn_refresh: UIButton! 

你可以直接把你的图像放在三种模式下

  // for normal state btn_refresh.setImage(UIImage(named: "xxx.png"), forState: UIControlState.Normal) // for Highlighted state btn_refresh.setImage(UIImage(named: "yyy.png"), forState: UIControlState.Highlighted) // for Selected state btn_refresh.setImage(UIImage(named: "zzzz.png"), forState: UIControlState.Selected) 

在你的button动作

  //MARK: button_refresh action @IBAction func button_refresh_touchup_inside(sender: UIButton) { //if you set the image on same UIButton sender.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal) //if you set the image on another UIButton youranotherbuttonName.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal) } 

对于任何使用Assets.xcassets和Swift 3的人来说,都是这样的(不需要.png)

 let buttonDone = UIButton(type: .Custom) if let image = UIImage(named: "Done") { self.buttonDone.setImage(image, for: .normal) } 

我更喜欢首先初始化variables的方法:

 let playButton:UIButton! var image:UIImage! 

然后在viewDidLoad中设置它们

 override func viewDidLoad { ... playButton = UIButton(type: .Custom) imagePlay = UIImage(named:"play.png") playButton.setImage(imagePlay, forState: .Normal) } 

从swift 3.0开始,正常状态已经被删除。你可以使用下面的命令来应用正常状态。

 myButton.setTitle("myTitle", for: []) 

是的,即使我们可以通过使用标志来改变UIButton的图像。

 class ViewController: UIViewController { @IBOutlet var btnImage: UIButton! var flag = 0 override func viewDidLoad() { super.viewDidLoad() //setting default image for button let image1 = UIImage(named: "share.png") as UIImage! self.btnImage.setImage(image1, for: .normal) } @IBAction func btnClick(_ sender: Any) { if flag == 0 { let image1 = UIImage(named: "image.png") as UIImage! self.btnImage.setImage(image1, for: .normal) flag = 1 } else { let image1 = UIImage(named: "share.png") as UIImage! self.btnImage.setImage(image1, for: .normal) flag = 0 } } } 

在这里,每次点击后你的button图像会交替改变。

在快速3.0

 @IBOutlet weak var selectionButton: UIButton! selectionButton.setImage(UIImage.addBlueIcon, for: .selected) 

你可以通过突出显示button来实现这一点,在右侧工具栏上的分解器内,你可以更新图像。 显然你也可以在代码中做到这一点,如前所述,但这是另一种select