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()

                }

            }

        }



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