2017-10-05 36 views
0

我使用UITableView來顯示來自領域的數據。我有兩種類型的第一排UIImageView和其他沒有UIImageView。如果形象UIImageView行的高度應爲207或UIImageView是零行的高度應爲64如何使用tableviewcell的動態高度

我的編碼:

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return msgs.count 
} 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! collCell 
    let msg = msgs[indexPath.row] 
    var decodeImgURL = "" 
    cell.lbl1.text = msg.content 

    decodeImgURL = msg.imgurl 

    if decodeImgURL == "none" { 
     cell.img.isHidden = true 
    } else { 

     let dataDecoded : Data = Data(base64Encoded:decodeImgURL,options: .ignoreUnknownCharacters)! 
     let decodedImage = UIImage(data: dataDecoded) 
     cell.img.image = decodedImage 

    } 
    return cell 
} 
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    let cell = tableView.cellForRow(at: indexPath) as! collCell 
    if cell.img.image != nil { 
     return 207 
    } else { 
     return 64 
    } 

} 

我得到一個錯誤的let cell = tableView.cellForRow(at: indexPath) as! collCell

+0

@Moritz確定我理解 –

回答

1

使用相同的數據在heightForRowAt如您在cellForRowAt使用:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 

    let msg = msgs[indexPath.row] 

    if msg.imgurl == "none" { 
     print("row \(indexPath.row) does NOT have an image") 
     return 64 
    } else { 
     print("row \(indexPath.row) DOES have an image") 
     return 207 
    } 

} 

Alternativel你可以使用自動佈局和約束來自動調整行的高度......但這是另一個話題。

+0

我更新了我的答案......看看你是否有有效的打印語句的行,有沒有圖像。 – DonMag

+0

非常感謝它的工作 –