Answers:
从您的Obc-C代码中,我认为您想为按钮设置图片,因此请尝试以下方式:
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)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
在Swift 4中,(Xcode 9)示例将按钮的图片打开或关闭(btnRec):
var bRec:Bool = true
@IBOutlet weak var btnRec: UIButton!
@IBAction func btnRec(_ sender: Any) {
bRec = !bRec
if bRec {
btnRec.setImage(UIImage(named: "MicOn.png"), for: .normal)
} else {
btnRec.setImage(UIImage(named: "MicOff.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)
按一下按钮
//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)
}
是的,甚至我们也可以通过使用标志来更改UIButton的图像。
class ViewController: UIViewController
{
@IBOutlet var btnImage: UIButton!
var flag = false
override func viewDidLoad()
{
super.viewDidLoad()
//setting default image for button
setButtonImage()
}
@IBAction func btnClick(_ sender: Any)
{
flag = !flag
setButtonImage()
}
func setButtonImage(){
let imgName = flag ? "share" : "image"
let image1 = UIImage(named: "\(imgName).png")!
self.btnImage.setImage(image1, for: .normal)
}
}
在这里,每次单击后,您的按钮图像都会交替更改。
在Swift 4.2和Xcode 10.1中
为所选的UIButton添加图像
button.addTarget(self, action: #selector(self.onclickDateCheckMark), for: .touchUpInside)//Target
button.setImage(UIImage.init(named: "uncheck"), for: UIControl.State.normal)//When selected
button.setImage(UIImage.init(named: "check"), for: UIControl.State.highlighted)//When highlighted
button.setImage(UIImage.init(named: "check"), for: UIControl.State.selected)//When selected
但是,如果要更改选定的按钮图像,则需要更改其选定状态。然后,只有选定的图像会出现在您的按钮中。
@objc func onclickDateCheckMark(sender:UIButton) {
if sender.isSelected == true {
sender.isSelected = false
print("not Selected")
}else {
sender.isSelected = true
print("Selected")
}
}
在迅速3.0中:
@IBOutlet weak var selectionButton: UIButton!
selectionButton.setImage(UIImage.addBlueIcon, for: .selected)