我正在尝试制作我的应用,以便当用户触摸UIImageView时会发出某种声音。但是,当播放该声音时,我希望将UIImageView.isUserInteractionEnabled指定为false。声音播放完毕后,我希望将UIImageView.isUserInteractionEnabled指定为true。当我运行以下代码时,即使我强制解包,我也会在卡类中出错。下面是包含我要禁用的图像视图的类。
class SecondViewController: UIViewController , UIGestureRecognizerDelegate {
@IBOutlet weak var imgPhoto: UIImageView!
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
imgPhoto.isUserInteractionEnabled = false
itemList[imageIndex].playSound()
}
}
这是playSound func所在的类。
import Foundation; import UIKit; import AVFoundation
class Card: NSObject
{
var player: AVAudioPlayer?
var svc = SecondViewController()
var image: UIImage
var soundUrl: String
init(image: UIImage, soundUrl: String, isActive:Bool = true) {
self.image = image
self.soundUrl = soundUrl
}
func playSound()
{
guard let url = Bundle.main.url(forResource: self.soundUrl, withExtension: "m4a") else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
player?.delegate = self
guard let player = player else { return }
player.prepareToPlay()
player.play()
audioPlayerDidFinishPlaying(player)
print("play")
} catch let error {
print(error.localizedDescription)
}
}
}
extension Card: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer){
svc.imgPhoto.isUserInteractionEnabled = true
}
}
答案 0 :(得分:1)
问题在于这一行:
var svc = SecondViewController()
svc
不是你的 SecondViewController,是imgPhoto
接口中的现有版本。相反,您正在使用空视图创建一个新的,独立的,最重要的空白视图控制器,因此其imgPhoto
为nil
,并且在您引用它时会崩溃。
您要做的是使用“委托”模式来保存对真实 SecondViewController的引用,以便您可以与之交谈。