我正在尝试制作播放/暂停按钮,在按下时自定义图像之间切换.这是代码的片段.
一切正常,但按钮不会改变.我也尝试使用.image属性而不是.setBackGroundImage方法,但是按钮在单击时变为空白.
这是代码
import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() var pauseImage:UIImage? var playImage:UIImage? @IBOutlet weak var btnPlayPause: UIBarButtonItem! @IBOutlet weak var sldVolume: UiSlider! @IBAction func sldVolumeChanged(sender: AnyObject) { audioPlayer.volume = sldVolume.value } @IBAction func actPressedPlayPause(sender: AnyObject) { if audioPlayer.playing { audioPlayer.pause() btnPlayPause.setBackgroundImage(playImage,forState: .Normal,barMetrics: .Default) } else { audioPlayer.play() btnPlayPause.setBackgroundImage(pauseImage,barMetrics: .Default) } } @IBAction func actStopPressed(sender: AnyObject) { audioPlayer.stop() audioPlayer.currentTime = 0 } override func viewDidLoad() { super.viewDidLoad() var pauseImagePath = NSBundle.mainBundle().pathForResource("pause",ofType: "png") pauseImagePath = pauseImagePath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) pauseImage = UIImage(contentsOfFile: pauseImagePath!) var playImagePath = NSBundle.mainBundle().pathForResource("play",ofType: "png") playImagePath = playImagePath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) playImage = UIImage(contentsOfFile: pauseImagePath!) var audioPath = NSBundle.mainBundle().pathForResource("minuetcminor",ofType: "mp3") audioPath = audioPath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) var error : NSError? = nil audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath!),error: &error) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
解决方法
这里有同样的问题!如果我们两个人为什么不工作感到困惑,我认为这是Swift 2 / Xcode 7 beta的变化
这样做:
btnPlayPause.image = UIImage(named: "myImage.png")
希望有所帮助!