我有一个自定义单元格的uitableview,名为
resultsCell
是的。它包含4个uiLabels和6个uiButtons,如下所示(我标记了每个框的类型):
uitableview中大约有10个这样的单元格,因此这些单元格当然可以重用。每当我上下滚动多次时,单元格中的每个uilabel都会完美地更新到每个单元格,但是uibutton并不总是正确更新,而是显示不同的值。每个按钮都链接到一个ibaction,该ibaction使用segue将用户重定向到不同的视图。如何修复不更新的ui按钮?或者有没有更好的方法不用扣子?
代码:
uiTableViewCell类:
class ResultsTableViewCell: UITableViewCell {
@IBOutlet weak var red1: UIButton!
@IBOutlet weak var red2: UIButton!
@IBOutlet weak var red3: UIButton!
@IBOutlet weak var redScore: UILabel!
@IBOutlet weak var blue1: UIButton!
@IBOutlet weak var blue2: UIButton!
@IBOutlet weak var blue3: UIButton!
@IBOutlet weak var blueScore: UILabel!
@IBOutlet weak var teamsLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
override func prepareForReuse() { //I tried doing this with no luck.
super.prepareForReuse()
red1?.setTitle("", for: .normal)
red2?.setTitle("", for: .normal)
red3?.setTitle("", for: .normal)
blue1?.setTitle("", for: .normal)
blue2?.setTitle("", for: .normal)
blue3?.setTitle("", for: .normal)
}
}
uitableview可重用单元代码出列
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCell") as! ResultsTableViewCell
let thisMatch = resultsDict[indexPath.row] as! [String:String]
cell.red1?.setTitle(thisMatch["red2"], for: .normal)
cell.red2?.setTitle(thisMatch["red2"], for: .normal)
cell.red3?.setTitle(thisMatch["red3"], for: .normal)
cell.blue1?.setTitle(thisMatch["blue1"], for: .normal)
cell.blue2?.setTitle(thisMatch["blue2"], for: .normal)
cell.blue3?.setTitle(thisMatch["blue3"], for: .normal)
cell.redScore?.text = thisMatch["redScore"]
cell.blueScore?.text = thisMatch["blueScore"]
if (playerID == thisMatch["red1"]) {
cell.red1?.underline()
} else if (playerID == thisMatch["red2"]) {
cell.red2?.underline()
} else if (playerID == thisMatch["red3"]) {
cell.red3?.underline()
} else if (playerID == thisMatch["blue1"]) {
cell.blue1?.underline()
} else if (playerID == thisMatch["blue2"]) {
cell.blue2?.underline()
} else if (playerID == thisMatch["blue3"]) {
cell.blue3?.underline()
}
return cell
}
这场比赛
{
"red1": "1234",
"red2": "4567",
"red3": "8901",
"blue1": "2345",
"blue2": "6789",
"blue3": "0123",
"redScore": "456",
"blueScore": "789",
}
按钮应显示的内容:
下划线扩展:
extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: (self.titleLabel?.text!.count)!))
self.setAttributedTitle(attributedString, for: .normal)
}
}