Swift实战-豆瓣电台,四歌曲列表的展现

观看地址 http://v.youku.com/v_show/id_XNzMwNDE0OTA4.html

这节的主要内容是如何利用cell展现获取到的数据。

首先申明两个数组来储存我们获取到的数据

var tableData:NSArray=NSArray()
var channelData:NSArray=NSArray()

tableData是主界面上歌曲列表要用的数据。所以在func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)这个方法中要返回tableData的数量

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        return tableData.count
} 

然后我们把tableData中的数据填充到主界面的TableView

let cell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "douban")
let rowData:NSDictionary=self.tableData[indexPath.row] as NSDictionary
cell.text=rowData["title"] as String
cell.detailTextLabel.text=rowData["artist"] as NSString

接着我们在显示缩略图的时候先给一张默认的图片

cell.image=UIImage(named:"detail.jpg")

然后我们去抓取网络图片,同样,是用异步的方式。为了提高性能,我们对获取的图片做了一个缓存

var imageCache = Dictionary<String,UIImage>()

通过图片的地址来缓存UIImage

        let url=rowData["picture"] as String
        let image=self.imageCache[url] as?UIImage
        if !image?{
            let imgURL:NSURL=NSURL(string:url)
            let request:NSURLRequest=NSURLRequest(URL: imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!,data:NSData!,error:NSError!)->Void in
                var img=UIImage(data:data)
                cell.image=img
                self.imageCache[url]=img
            })
        }else{
            cell.image=image
        }  

本节高清视频和代码下载地址

http://pan.baidu.com/s/1sjHd5qX

下一节,我们将一起学习一下播放歌曲和展示当前歌曲图片

Swift实战-豆瓣电台系列

Swift实战-豆瓣电台(一)准备

Swift实战-豆瓣电台(二)界面布局

Swift实战-豆瓣电台(三)获取网络数据