【问题标题】:Switch on custom table view cell won't stay highlighted打开自定义表格视图单元格不会保持突出显示
【发布时间】:2018-06-20 07:48:59
【问题描述】:

我在自定义表格视图单元格上有一个开关,允许用户注册通知并遇到以下问题:

如果用户通过单击索引 0 处的开关打开通知,然后滚动到底部(将索引 0 推离页面)然后向上滚动,则他们刚刚打开的索引 0 处的选项将再次显示关闭。

似乎单元格会记住第一次加载时的设置(关闭开关),并在单元格滚动离开页面然后重新打开时恢复到该设置。

如何让自定义单元格上的开关记住它已被更改?可能是细胞被重复使用的问题?

【问题讨论】:

  • 您需要我们的数据模型的某些部分来“记住”每个数据模型项的开关设置,然后在cellForRow 委托方法中相应地设置开关。每次调用 cellForRow 时都必须进行设置。

标签: swift uitableview uiswitch


【解决方案1】:

您需要确保已存储数据以防止出现问题。我会在viewDidLoad 中检查一个值,在选择开关时更新该值,然后在cellForRow 实例化该行时分配该值。

var toggleValue : Bool? // set variable to be used in class

override func viewDidLoad() {
    // TODO: load value from wherever you store this value... User Defaults, Core Data, etc.,
    if let value = storedData.value {
        toggleValue = value
    } else { toggleValue = false }

}

然后当你加载单元格时:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! YourCustomCell
    if indexPath.row == 0 {
        cell.switch.setOn(toggleValue!, animated: false)
    }
}

然后在您处理开关切换的函数中,您需要更新toggleValue 变量的值。像这样的:

// obviously this wont work on it's own. You'll need an action or to observe the switch and call the function when appropriate.
func doSwitch() { 
    // check toggleValue and swap true/false
    if switch.isOn {
        toggleValue = false
    } else { toggleValue = true } 
    // TODO: store the value somewhere like User Defaults  
    switch.setOn(toggleValue!, animated: true) // perform toggle
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多