将正确的图像加载到详细视图

时间:2018-10-22 13:53:23

标签: swift avfoundation

我有一个播放音乐的TableView应用。这些音轨的名称为:0.mp3、1.mp3等。它们在局部视图中播放,在这里我还需要封面的图像。我将封面图片命名为:0.png,1.png等。

我尝试使用代码加载正确的图像:

self.bookImage.image = UIImage(named: ("/\(trackID!).png"))

但它不起作用。

还有更多我的代码:

import UIKit
import AVFoundation

class AudioPlayerVC: UIViewController {

    var trackID: Int!
    var audioPlayer:AVAudioPlayer!

    @IBOutlet var bookImage: UIImageView! 

    @IBAction func play(_ sender: AnyObject) {
        if !audioPlayer.isPlaying{
            audioPlayer.play()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.bookImage.image = UIImage(named: ("/\(trackID!).png"))
        trackLbl.text = "Track \(trackID!)"

        let path: String! = Bundle.main.resourcePath?.appending("/\(trackID!).mp3")
        let mp3URL = NSURL(fileURLWithPath: path)
        do
        {
            audioPlayer = try AVAudioPlayer(contentsOf: mp3URL as URL)
            audioPlayer.play()
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您需要

self.bookImage.image = UIImage(named:"\(trackID).png")

self.bookImage.image = UIImage(named:"\(trackID)")

答案 1 :(得分:0)

首先,打开引号后不需要/字符。

self.bookImage.image = UIImage(named:"\(trackID).png")

应该可以正常工作。

答案 2 :(得分:0)

1)请将您的图像添加到Assets.xcassets

2)在Assets.xcassets中命名图像,例如0、1、2、3

3)编写代码:

let trackId = String(trackId)
self.bookImage.image = UIImage(named: trackId)