【发布时间】:2021-12-24 14:37:39
【问题描述】:
我有点卡住了。我有一个自定义的UIView,其中包含一个计时器和一个UIImageView,该计时器以恒定的时间间隔触发并从一组图像中更改图像。当我将它嵌入到任何其他 UIView 中时,此自定义视图工作正常并且性能良好。它以规定的速度更改图像并且没有任何问题。它可以按我的意愿工作。
然而,这个完全相同的视图,当放置在如下所示的UITableVieCell 中时,只会渲染第一张图像并且不会改变。我已经确认计时器正在触发,并且图像视图正在通过打印对UIImageView.image 的引用来更改其引擎盖下的图像。也就是说,当嵌入到UITableViewCell 中时,我的自定义UIView 正在触发其计时器,而此自定义视图中的UIImageView 认为它正在更改其图像。这让我相信这是一个显示问题,而不是数据设置问题。
因此,这里是尝试过的:
- 我试过用
DispatchQueue.main.async{}包裹它 - 添加一个委托,以便我的
UIViewController可以在定时器触发时调用tableView.reloadData() - 在我的
prepareForReuse上删除multiImageView.images的设置器
下方的自定义单元格
import UIKit
import SnapKit
final internal class MultiImageCell: UITableViewCell {
// MARK: - UI Elements
public var multiImageView: MultiPartImageView = MultiPartImageView()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
//Setup Cell
selectionStyle = .none
//Setup Section Title View
multiImageView.rotationSpeed = 0.3
contentView.addSubview(multiImageView)
//Setup Constraints
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
accessoryType = .none
multiImageView.images = []
}
override func layoutSubviews() {
super.layoutSubviews()
setupConstraints()
}
// MARK: - Functions
private func setupConstraints() {
//Setup Section View Constraints
multiImageView.snp.remakeConstraints({ (make) in
make.edges.equalToSuperview().inset(16)
make.width.height.equalTo(240)
})
}
}
在单元格上设置图像
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Check for Cell
guard let row = viewModel.row(at: indexPath) else {
return UITableViewCell()
}
// Setup Cell
let cell = tableView.dequeueReusableCell(withIdentifier: row.cellReuseIdentifier,
for: indexPath)
cell.textLabel?.text = viewModel.title(for: row, indexPath: indexPath)
cell.detailTextLabel?.text = row.detailText
cell.accessoryView = row.accessoryView
cell.accessoryType = row.accessoryType ?? .none
cell.imageView?.image = row.image
switch RowStyle(rawValue: row.cellReuseIdentifier) {
case .multiImageCell:
guard let multiImageCell: MultiImageCell = cell as? MultiImageCell else {
return cell
}
guard let multiImageRow: MultiImageRow = row as? MultiImageRow else {
return cell
}
multiImageCell.multiImageView.images = multiImageRow.images
default:
break
}
return cell
}
【问题讨论】:
-
会不会是因为你在prepareForReuse方法上重置了
multiImageView.images = []图片? -
您不会在将图像添加到单元格的位置显示代码。
-
@Claudio 在我上面尝试过的项目列表中,我尝试删除该行但没有成功。
-
@BrandonStillitano 很难说它是什么,你能提供一个可重复的例子吗?顺便说一句,我认为您不需要重新制定 layoutSubviews 的约束
-
返回单元格前添加这一行,multiImageCell.multiImageView.images = multiImageRow.images
标签: ios swift uitableview uiimageview dispatch-queue