【发布时间】:2023-03-05 03:23:01
【问题描述】:
我有一个自定义 UITableViewCell,它在左侧显示一个圆形图像。由于 UITableViewCell 提供的默认 UIImageView 与行的高度相同,因此图像最终几乎接触。我想稍微缩小图像以创建一些额外的填充。
我能够使用以下代码使其工作
override func layoutSubviews() {
super.layoutSubviews()
// Make the image view slightly smaller than the row height
self.imageView!.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
// Round corners
self.imageView!.layer.cornerRadius = self.imageView!.bounds.height / 2.0
self.imageView!.layer.borderWidth = 0.5
self.imageView!.layer.borderColor = UIColor.gray.cgColor
self.imageView!.layer.masksToBounds = true
self.imageView!.contentMode = .scaleAspectFill;
self.updateConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView!.image = nil
self.layoutSubviews()
}
这仅适用于表格视图中首次出现在屏幕上时显示的单元格。一旦我滚动(即出列可重复使用的单元格),就不再应用转换。下图显示了表格视图的左侧。我已经捕获了原始单元格转换为重复使用单元格的区域。
为了完整起见,这是我的 tableView(cellForRowAt:) 函数
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.itemTableView.dequeueReusableCell(withIdentifier: "ItemCell") as! InventoryItemTableViewCell
if let items = self.displayedItems {
if indexPath.row < items.count {
let item = items[indexPath.row]
cell.item = item
cell.textLabel!.text = items[indexPath.row].partNumber
cell.detailTextLabel!.text = items[indexPath.row].description
if let quantity = items[indexPath.row].quantity {
cell.quantityLabel.text = "Qty: \(Int(quantity))"
}
else {
cell.quantityLabel.text = "Qty: N/A"
}
if let stringImageBase64 = item.imageBase64 {
let dataDecoded: Data = Data(base64Encoded: stringImageBase64, options: .ignoreUnknownCharacters)!
cell.imageView!.image = UIImage(data: dataDecoded)
}
else {
cell.imageView!.image = blankImage
}
}
}
return cell
}
我尝试了其他方法,例如使用图像视图的插图,但没有效果。
问题
为什么在创建表格时将转换应用于原始单元格,而不应用于任何重复使用的单元格?我应该以不同的方式处理这个问题吗?
【问题讨论】:
-
重用cell时是否调用layoutSubviews?
标签: ios swift uitableview tableview