【问题标题】:UISwitch duplicating/weird overlay in CollectionViewCells when scrolling [duplicate]滚动时UISwitch在CollectionViewCells中重复/奇怪的覆盖[重复]
【发布时间】:2019-05-30 17:22:23
【问题描述】:

我以编程方式在集合单元格中创建了 UISwitches,并且随着滚动的发生,这些开关被一遍又一遍地添加,这导致了半切换(猜测是因为另一个 UISwitch 就在它的正下方)。

这是创建 UISwitch 的整个过程。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FlagCell", for: indexPath)

    let switchOnOff = UISwitch()

    switchOnOff.translatesAutoresizingMaskIntoConstraints = false
    switchOnOff.setOn(true, animated: true)

    cell.contentView.addSubview(switchOnOff)

    NSLayoutConstraint(item: switchOnOff, attribute: .trailing, relatedBy: .equal, toItem: cell, attribute: .trailing, multiplier: 1, constant: -10).isActive = true

    NSLayoutConstraint(item: switchOnOff, attribute: .centerY, relatedBy: .equal, toItem: cell, attribute: .centerY, multiplier: 1, constant: 0).isActive = true

    return cell
}

我可以通过 Storyboard 做到这一点,但也许你们可能有一个以编程方式完成的解决方案。

【问题讨论】:

  • 您不应该在cellForItemAt 中添加子视图。创建一个带有开关的自定义单元格类。
  • 谢谢@rmaddy!我能够让它工作。你介意提供一个简短的解释吗?

标签: ios swift uicollectionview uiswitch


【解决方案1】:

正如 rmaddy 建议的那样,创建一个自定义单元类解决了这个问题。

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FlagCell

并移动该类中添加的所有子视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2018-05-29
    • 2011-05-13
    相关资源
    最近更新 更多