Swift 为什么UITableView为每个单元格显示相同的视图?
我一直在尝试在Swift 为什么UITableView为每个单元格显示相同的视图?,swift,Swift,我一直在尝试在UITableView的第一个单元格中实现UISegmentedControl,但它在第一个单元格之后的每个单元格中都显示了它的效果。我该如何解决这个问题 import UIKit class InfoTableViewController: UITableViewController { convenience init() { self.init(style: UITableView.Style.grouped) } var i
UITableView
的第一个单元格中实现UISegmentedControl
,但它在第一个单元格之后的每个单元格中都显示了它的效果。我该如何解决这个问题
import UIKit
class InfoTableViewController: UITableViewController {
convenience init() {
self.init(style: UITableView.Style.grouped)
}
var image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 5
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
if indexPath.row == 0 {
let genderItems = ["Male", "Female"]
let genderControl = UISegmentedControl(items: genderItems)
genderControl.addTarget(self, action: #selector(genderChanged), for: .valueChanged)
cell.contentView.addSubview(genderControl)
genderControl.translatesAutoresizingMaskIntoConstraints = false
genderControl.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
genderControl.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
}
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0{
return view.frame.height/3
}
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let imageView: UIImageView = UIImageView()
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.image = self.image
return imageView
}
return nil
}
@objc func genderChanged(){
}
}
解决方案#1
去掉这个
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 5
}
在这里返回5
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 5
}
解决方案#2
替换
if indexPath.row == 0 {
到
在这两个选项中,如果要返回另一个所需的单元格,则应该为该选项实现else
同时将此行移动到viewDidLoad
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")