행이 아닌 섹션에 셀이있는 맞춤형 UITableView가 있습니다. 총 셀 수는 5 개입니다. 각 셀에는 단추가 있고 다섯 번째 셀 단추 (tableButton)에 나머지 제목이 달려 있습니다.Swift : cellForRowAtIndexPath에서 예기치 않은 결과가 발생했습니다.
이 코드는 아래 코드와 모두 잘 작동합니다. 첫 번째 4 셀에는 처음에 코드 당 올바른 제목이 있습니다. 그러나 5 번째 셀 (예상 제목 있음)을 아래로 스크롤 한 다음 첫 번째 셀까지 스크롤하면 첫 번째 셀이 이제 다섯 번째 셀에만 한정된 제목으로 변경되었습니다.
if cell.tableButton.tag == 4 조건문에 print 문을 추가했으며 다섯 번째 셀까지 스크롤 할 때마다 인쇄됩니다.
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
각 섹션이 1 셀인 5 섹션, 총 5 셀. –