Swift中使用SDWebImage在自定义TableView单元格加载显示图片
Solution: Load QR Image with SDWebImage in Collapsible TableView Detail Cell
Hey there! Let's get that QR image loaded using SDWebImage in your collapsible table view's detail cell. Here's how to fix it step by step:
Step 1: Import SDWebImage
First, make sure you add the SDWebImage import to your view controller file (I didn't see it in your provided code):
import SDWebImage
Step 2: Update the cellForRowAt Method
Modify your table view data source method to handle image loading for the detail cell. We'll use SDWebImage's sd_setImage(with:placeholderImage:) method to load the QR image, plus add safeguards for invalid URLs and cell reuse issues.
Here's the updated code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Handle Header Cell if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop // Hide detail-only elements to avoid reuse bugs cell.qrCodeImage.isHidden = true cell.lblTerm.isHidden = true return cell } // Handle Detail Cell let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms // Load QR Image with SDWebImage let qrImageUrlString = sectionDataObj[indexPath.section].qrImage if let qrImageUrl = URL(string: qrImageUrlString) { // Replace placeholder image names with your project's actual assets (or pass nil if not needed) cell.qrCodeImage.sd_setImage(with: qrImageUrl, placeholderImage: UIImage(named: "placeholder-qr")) { [weak self] image, error, cacheType, url in guard let self = self else { return } if let error = error { print("QR Image Load Failed: \(error.localizedDescription)") // Set a fallback image if loading fails cell.qrCodeImage.image = UIImage(named: "fallback-qr") } } } else { // Handle invalid URL case cell.qrCodeImage.image = UIImage(named: "invalid-qr") } // Show detail-only elements cell.qrCodeImage.isHidden = false cell.lblTerm.isHidden = false return cell }
Key Notes:
- Cell Reuse Fix: We explicitly hide/show elements in header/detail cells to prevent old content from appearing when cells are reused.
- URL Validation: We check if the
qrImagestring can be converted to a valid URL before attempting to load. - Error Handling: Added a completion block to handle loading errors and set fallback images.
- Placeholder Images: Replace the placeholder image names with assets that exist in your project (remove the parameter if you don't need placeholders).
内容的提问来源于stack exchange,提问作者anuj tiwari
相关产品推荐
相关产品推荐

