ios - 如何为每首歌曲添加一个 UILabel?

标签 ios swift

我目前可以获取正在播放的任何歌曲,并获取一首歌曲信息的 UILabel,但是当歌曲发生变化时,新歌曲的信息不会添加到 uitable 中的新单元格中。每次播放新歌曲时,如何将新歌曲信息添加到新单元格?

 override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
    musicPlayer.beginGeneratingPlaybackNotifications()

    playButton = UIButton()
    let image = "playbutton.png"
    playButton.setImage(UIImage(named:image), forState: .Normal)
    playButton.addTarget(self, action: "play:", forControlEvents: UIControlEvents.TouchUpInside)

    // Do any additional setup after loading the view.
}

func getNowPlayingItem() {
    if let nowPlaying = musicPlayer.nowPlayingItem {
        let title = nowPlaying[MPMediaItemPropertyTitle] as? String
        let artist = nowPlaying[MPMediaItemPropertyArtist] as? String
        let album = nowPlaying[MPMediaItemPropertyAlbumTitle] as? String
        println("Song: \(title)")
        println("Artist: \(artist)")
        println("Album: \(album)")
        println("\n")


        self.add = [Play(name: "\(title!)\n\(artist!)\n\(album!)")]
        self.table.rowHeight = UITableViewAutomaticDimension
        self.table.estimatedRowHeight = 44.0

    }


}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.add.count
    //return count of objects in array
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: UITableViewCell = self.table.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    var play: Play

    play = add[indexPath.row]

    cell.textLabel?.text = play.name

    cell.textLabel?.numberOfLines = 3;
    cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping


    playButton.tag = indexPath.row


    return cell
}

最佳答案

您可以注册 MPMusicPlayerControllerNowPlayingItemDidChangeNotification 通知,详见 https://developer.apple.com/library/ios/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/UsingMediaPlayback/UsingMediaPlayback.html#//apple_ref/doc/uid/TP40008765-CH100-SW1

然后在通知选择器中,调用 getNowPlayingItem 将新歌曲添加到您的表中。

您还必须使用新的歌曲信息创建一个新的 Play 对象并将其添加到您的 self.add 数组中。

let name = title + "\n" + artist + "\n" + album + "\n";
self.add.append(Play(name: name));

关于ios - 如何为每首歌曲添加一个 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32341859/

相关文章:

IOS5 __block 变量在范围外抛出 EXC_BAD_ACCESS

ios - 为什么我的 AVAudioPlayer 不播放?

ios - UITabBar 有问题

arrays - 获取数组的总和,保存到核心数据,并在应用程序重新打开后从总和开始?

swift - 避免使用样板代码在 viewDidLoad 中设置 UI

ios - 尝试将平移手势应用于 UITableViewCell 但失败了,为什么?

ios - 核心蓝牙 : Getting error even if data is written into writable characteristics

ios - tableview 单元格操作问题 xcode

具有 '\uxxxx' 形式的 iOS 本地化 : Unicode character escape sequences, 不起作用

swift - 在 Swift 中使用正则表达式