我有一个自定义的UITableView与部分中的单元格而不是行,总共5个单元格。每个单元格都有一个按钮,我希望第五个单元格按钮(tableButton)具有与其他标题不同的标题。Swift:意外的结果cellForRowAtIndexPath
这一切都工作正常,我有下面的代码,前4个单元格最初有正确的标题为每个代码。但是,当我向下滚动第5个单元格(其具有期望的标题),然后向后滚动到第一个单元格时,第一个单元格现在已经变为标题,以专用于第五个单元格。
我在if cell.tableButton.tag == 4条件中添加了打印语句,每次向下滚动到第五个单元格时都会打印它。
import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.gray.cgColor
cell.tableButton.tag = indexPath.section
if indexPath.section == 4 {
cell.tableTitle.isHidden = true
cell.tableButton.setTitle("Special", for: .normal)
} else {
cell.tableButton.setTitle("Normal", for: .normal)
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 15))
returnedView.backgroundColor = UIColor.groupTableViewBackground
return returnedView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 15
}
}
CustomCell.swift:
import UIKit
class CustomCell: UITableViewCell {
@IBOutlet weak var tableButton: UIButton!
@IBOutlet weak var tableTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
也许细胞的状态已经改变。在所有情况下用'[]'替换'.normal' – penatheboss
你有5个单元,5个单元? – iAviator
5个部分,每个1个细胞,共5个细胞。 –