IOS Swift TableViewCell 加载网络图片后图片高度

     有时候TableView需要加载网络图片,但网络图片的大小不一,所以显示的时候需要根据图片的大小动态的改变TableViewCell 的高,如下图所示:

  

     如果要实现右图的效果:
    需要建立一个数组,用于保存每个cell的高度,可以给一个默认值,在网络请求图片后,根据返回的imaga判断图片的尺寸大小,重新修改数组里面对应的cell的高。我用的是

Alamofire第三方库请求数据,一下是关键代码:

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        return  CGFloat(self.testHList[indexPath.row])//testHList存放cell的高,更新cell

    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("testCellIndentifier", forIndexPath: indexPath) as! TestTableViewCell

        cell.titleLabel.text = "Uncomment the following line to preserve selection between presentations"

        request(.GET,testList[indexPath.row]).response { (_, response, data, _) -> Void in

            if  let image = UIImage(data: data!) {

                cell.testImageView.image = image

                let screen_width = UIScreen.mainScreen().bounds.width

                let oldHeight = self.testHList[indexPath.row]

                var newHeight = Int(image.size.height)

                if image.size.width > screen_width {

                     let aspect = image.size.height / image.size.width

                    newHeight = Int(screen_width * aspect)

                }

                if oldHeight != newHeight {

                    self.tableView.beginUpdates()

                    self.testHList[indexPath.row] = newHeight//设置cell的高时需要beginUpdates()和endUpdates()之间,这样界面才能刷新

                    self.tableView.endUpdates()

                }

            }

        }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章