【发布时间】:2021-06-18 02:30:10
【问题描述】:
我正在尝试在 UITableView 的单元格的第一行添加一个徽章。当应用程序在 iPhone SE 2 等小型设备上打开时,我的问题出现了,其中 UITableView 需要向下滚动以显示最后一行。当我向下滚动到最后一行时,它还具有仅用于第一行的徽章。它不会在第一次向下滚动时显示,而是在多次上下滚动时显示。
// 将显示
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let news = twoDimensionalArray[indexPath.section].options[indexPath.row]
print("indexPath.section: \(indexPath.section) - indexPath.row: \(indexPath.row) - news \(news)")
let hub = BadgeHub(view: cell)
if indexPath.section == 0 && indexPath.row == 0 {
hub.setCircleAtFrame(CGRect(x: 120, y: 10, width: 25, height: 25))
hub.setCount(newsCount!)
}
else {
hub.setCount(0)
hub.checkZero()
}
}
// cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, for: indexPath) as? MenuViewCell {
cell.selectionStyle = .none
var settingOptionName = ""
if UserDefaults.standard.bool(forKey: ("isDoneWithGuide")) == false {
}
if (indexPath.row == 12) && (self.isLogin) {
settingOptionName = twoDimensionalArray[0].extraString[0]
} else {
settingOptionName = twoDimensionalArray[indexPath.section].options[indexPath.row]
}
print("settingOptionName \(settingOptionName ?? "")")
//cell.textLabel?.text = settingOptionName
cell.setTitleLabel(text: settingOptionName)
if showIndexPaths {
//cell.textLabel?.text = "\(settingOptionName) Section:\(indexPath.section) Row:\(indexPath.row)"
cell.setTitleLabel(text: "\(settingOptionName) Section:\(indexPath.section) Row:\(indexPath.row)")
}
return cell
}
return UITableViewCell()
}
// UITableViewCell
class MenuViewCell : UITableViewCell {
@IBOutlet weak var titleLabel : UILabel!
func setTitleLabel(text : String) {
self.titleLabel.text = text
}
}
【问题讨论】:
-
您为什么要在
willDisplay中这样做?您应该在cellForRow中执行此操作。 -
另外,你能告诉我
BadgeHub做了什么吗? -
@Sweeper 我在
willDisplay上执行此操作,因为cellForRow仅在用户第二次显示TableView 时显示徽章。 BadgeHub -
您绝对应该将添加徽章的代码放入
cellForRow。你还应该在你的单元格类中保留一个BadgeHub的实例,而不是每次都创建一个新实例,这就是导致这种行为的原因。你能展示你的单元格类和你的cellForRow吗? -
@Sweeper 更新了帖子。谢谢。
标签: ios swift uitableview