滚动UITableView – Swift时,UISwitch多次添加到UITableViewCell

我正在使用swift中的UITableView创建一个事件菜单,其中大部分是以编程方式完成的,对于事件菜单中的一些选项,我希望从用户那里收到一个布尔值(或是/否) – 所以一个开关将完美。 我基于单元格标签文本和部分通过cell.accessoryView添加交换机 – 因为我只想在2个特定行上切换。 问题是交换机被添加,然后当向下滚动,然后回到原始交换机时,现在在我没有指定的行上有第二个额外的开关,然后我向下滚动到底部和同样的事情那里。 首先,我想知道是否有更好的方法将开关添加到特定行(使用代码,因为单元格是以编程方式创建的),而且,为什么会发生这种情况? 以下代码的一些片段:

 class PrivateNewClientController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var menuTable: UITableView! let mainOptions = ["Client Name", "Invoicing Email", "Invoicing Address"] let dateOptions = ["All Day", "Starts", "Ends", "Time Zone"] let alertOptions = ["How Many Classes", "Shown on Calendar As", "Alert by Email", "Alert by Text"] let billingOptions = ["Tax Included", "Billing Options"] let textCellIdentifier = "TextCell" let NumberOfSections = 4; //For sections to have different amount of rows let numberOfRowsAtSection: [Int] = [3, 4, 4, 2] override func viewDidLoad() { super.viewDidLoad() //Set the table views delegate and data source to be this class itself menuTable.delegate = self menuTable.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NumberOfSections } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows: Int = 0 if section  UIView? { let spacer: UILabel = UILabel() spacer.backgroundColor = UIColor(red: CGFloat(240/255.0), green: CGFloat(240/255.0), blue: CGFloat(244/255.0), alpha: CGFloat(1.0)) return spacer } /*Adding UISwitches here*/ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell let row = indexPath.row //Configure the switches for swipe options let allDaySwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0)); allDaySwitch.on = false let gstSwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0)); gstSwitch.on = false //Assigns row labels based on sections if(indexPath.section == 0) { let rowTitle = mainOptions[row] //Add swipe switches if(rowTitle == "All Day") { cell.accessoryView = allDaySwitch } cell.textLabel?.text = rowTitle } else if(indexPath.section == 1) { let rowTitle = dateOptions[row] cell.textLabel?.text = rowTitle } else if(indexPath.section == 2) { let rowTitle = alertOptions[row] cell.textLabel?.text = rowTitle; } else { let rowTitle = billingOptions[row] //Add swipe switches if(rowTitle == "Tax Included") { cell.accessoryView = gstSwitch } cell.textLabel?.text = rowTitle } return cell } } 

如果条件不匹配,将accessoryView设置为nil:

 if(rowTitle == "All Day") { cell.accessoryView = allDaySwitch }else{ cell.accessoryView = nil }