【发布时间】: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