【发布时间】:2020-01-20 10:31:30
【问题描述】:
我在 tableView 中滚动时遇到问题。我在项目中实现了书签,一切正常,除了滚动时。当它第一次运行时,它会调用 API 来检查该项目是否已添加书签。如果加了书签,则显示它显示填充的图像,如果没有,则显示未填充的图像。第一次加载时它工作正常,但是当我滚动书签按钮图像时会发生变化。
我尝试在 CustomTableViewCell 上使用 prepareForReuse 来解决这个问题,并且只在 cellforRow 上渲染按钮图像,但没有成功。
这里是 MainViewController:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let itemCell = tableView.dequeueReusableCell(withIdentifier: "NewPodcastTableViewCell", for: indexPath) as! NewPodcastTableViewCell
let allMaterial = materials[indexPath.row]
itemCell.setMaterials(materials: allMaterial)
itemCell.delegate = self
return itemCell
}
extension BrowseViewController: ViewBookmarkedDelegate {
func setBookmark( refId: String, isBookmarking: Bool, refType: String, refSubType: String) {
let query = SetBookmarkMutation(refId: refId, refType: "material", isBookmarking: true, refSubType: refSubType)
Apollo.shared.client.perform(mutation: query ) { results, error in
if var bookmarked = results?.data?.bookmark {
print(refId,bookmarked,"onUnbookmark")
} else if let error = error {
print("Error loading data \(error)")
}
}
}
func setUnbookmark(refId: String, isBookmarking: Bool, refType: String, refSubType: String) {
let query = SetBookmarkMutation(refId: refId, refType: "material", isBookmarking: false, refSubType: refSubType)
Apollo.shared.client.perform(mutation: query ) { results, error in
if var bookmarked = results?.data?.bookmark {
print(refId,bookmarked,"onUnbookmark")
} else if let error = error {
print("Error loading data \(error)")
}
}
}
}
这里是 CustomTableViewCell
protocol ViewBookmarkedDelegate {
func setBookmark( refId: String, isBookmarking: Bool, refType: String, refSubType: String)
func setUnbookmark( refId: String, isBookmarking: Bool, refType: String, refSubType: String)
}
var delegate: ViewBookmarkedDelegate?
@IBOutlet weak var bookmarkButton: UIButton!
@IBAction func bookmarkButtonTapped(_ sender: UIButton) {
if (self.materials?.fragments.materialFields.bookmark?.bookmarked == false){
self.bookmarkButton.setImage(#imageLiteral(resourceName: "bookmarkEmpty"), for: .normal)
} else if (self.materials?.fragments.materialFields.bookmark?.bookmarked == true) {
self.bookmarkButton.setImage(#imageLiteral(resourceName: "Bookmark Filled"), for: .normal)
}
func setMaterials(materials: GetMaterialsByTypeQuery.Data.AllMaterial) {
self.materials = materials
}
override func prepareForReuse() {
super.prepareForReuse()
self.bookmarkButton.setImage(nil, for: .normal)
}
知道如何解决这个问题吗?
提前谢谢你。
【问题讨论】:
-
尝试使用 indexpath 在
cellForRowAt中设置书签,这样当它滚动时它会保持正确单元格的轨道 -
谢谢。它解决了这个问题。 :)
-
你能把它标记为正确答案吗:)
标签: ios swift iphone uitableview uibutton