3の倍数と3の数字がつく数字だけ画像を表示 & 音声を再生させます、Swift初心者には良い練習課題になりそう(適当)
Contents 非表示
実装
Storyboard
ViewController
import UIKit
import AVFoundation
final class HomeViewController: UIViewController {
// MARK: - Properties
@IBOutlet private weak var countLabel: UILabel!
@IBOutlet private weak var ahoImageView: UIImageView!
@IBOutlet private weak var incrementButton: DesignableButton!
private var count = 0
private var audioPlayer: AVAudioPlayer?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupAudioPlayer()
}
private func setupAudioPlayer() {
guard let audioPath = Bundle.main.path(forResource: "three_aho", ofType: "mp3") else {
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath))
audioPlayer?.prepareToPlay()
} catch {
print("Error")
}
}
@IBAction func incrementCountAction(_ sender: Any) {
count += 1
countLabel.text = String(count)
if count.isMultiple(of: 3) || String(count).contains("3") {
ahoImageView.image = UIImage(named: "nabeatsu")
audioPlayer?.play()
} else {
ahoImageView.image = nil
}
}
}
この記事は役に立ちましたか?
貴重なフィードバックありがとうございます!