【问题标题】:UITableViewCell not updating UISwitch when selecting row选择行时 UITableViewCell 不更新 UISwitch
【发布时间】:2019-11-07 10:30:08
【问题描述】:

我有一个UITableViewCell,其中包含一堆UISwitches。我希望开关根据用户选择的行打开/关闭,数据正在传递到我的单元格但开关状态没有更新。

我使用的是基本的 MVC,Storyboard 有一个 TableView > TableViewCell > Label |界面切换

控制器:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

var testList = [1,2,3,4,5]
@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    table.tableFooterView = UIView()
    table.delegate = self
    table.dataSource = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return testList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
    //Turn them all on at start
    cell.setSwitch(rowSelected: true)
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
    cell.setSwitch(rowSelected: false)
}

}

开关单元

类 SwitchCell: UITableViewCell {

@IBOutlet weak var uiswitch: UISwitch!
@IBOutlet weak var label: UILabel!

func setCell(number: Int){
    label.text = String(number)
}

func setSwitch(rowSelected:Bool) {
    uiswitch.setOn(rowSelected, animated: true)
}

}

我知道我可以让 UISwitch 变得难以处理,但我正在考虑在用户选择行时更改它的状态。

【问题讨论】:

    标签: swift xcode


    【解决方案1】:
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell") as! SwitchCell
        cell.setSwitch(rowSelected: false)
    }
    

    不正确。使用此代码,您不会选择所需的单元格。

    你应该这样做:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let cell = tableView.cellForRow(at: indexPath) as! SwitchCell
        cell.setSwitch(rowSelected: false)
    }
    

    【讨论】:

      【解决方案2】:

      首先,我们不会在didSelectRowAt 方法中将cell 出队。永远不要那样做。这将使一个全新的单元格出列,并且不会反映您在其中所做的任何更改。

      所以删除tableView(_: didSelectRowAt:)方法的代码。

      其次,您可以像这样使用 setSelected(_:animate:) 方法根据SwitchCell's 定义中的单元格选择简单地处理UISwitch 状态,

      class SwitchCell: UITableViewCell {
          @IBOutlet weak var uiswitch: UISwitch!
      
          override func setSelected(_ selected: Bool, animated: Bool) {
              super.setSelected(selected, animated: animated)
              uiswitch.setOn(selected, animated: true)
          }
      
          //rest of the code...
      }
      

      为避免庞大的代码,请在自定义 cell 本身中执行所有 cell 布局,而不是在 delegatedataSource 方法中执行。这只会让你ViewController 更重且非模块化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-24
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多