ios - 自定义图像和开关未在正确位置的集合视图控制器中显示
问题描述
我的要求是,我需要在集合视图控制器中填充 10 个电池,并且需要在第 6 个电池状态下显示电池状态,在第 7 个电池需要切换。剩余的电池不需要显示电池状态和开关。我正在通过编程方式添加这两个(电池状态和开关)。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if indexPath.row == 6 {
let percentage: CGFloat = 0.4
let imageview:UIImageView=UIImageView(frame: CGRect(x: 10, y: 50, width: 30, height: 18))
let img : UIImage = UIImage(named:"batteryIcon")!
imageview.image = img
let batteryView = UIView.init(frame: CGRect(x: 10, y: 50, width: 30, height: 18))
cell.addSubview(batteryView)
let colorRect = CGRect(x: batteryView.bounds.origin.x, y: batteryView.bounds.origin.y, width: batteryView.bounds.width * percentage, height: batteryView.bounds.height)
let coloredView = UIView(frame: colorRect)
coloredView.backgroundColor = UIColor.green
batteryView.addSubview(coloredView)
cell.contentView.addSubview(imageview)
} else if indexPath.row == 7 {
let switchDemo = UISwitch(frame: CGRect(x: 10, y: 40, width: 37, height: 18))
switchDemo.isOn = true
switchDemo.setOn(true, animated: false)
switchDemo.transform = CGAffineTransform(scaleX: 0.70, y: 0.70)
switchDemo.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
cell.contentView.addSubview(switchDemo)
}
return cell
}
在这里工作正常。但问题是当我调用“collectionView.reloadData()”而不是显示电池状态并切换第 6 和第 7 电池时,这两个电池也出现在其他电池中。
解决方案
推荐阅读
- chromium - 启用 Chromium 与 Google 帐户同步
- sql - 选择在一周中的特定日期或一个月中的特定日期发生事件的所有条目
- javascript - 如何使用 Javascript 将 URL 作为可点击链接添加到标题中
- arduino - ESP-01 客户端无法访问 NodeMCU 网络服务器(连接被拒绝)
- python - Python pandas:交换 DataFrame 切片的列值
- mysql - 如何使用 MySQL 从查询结果中删除 lrm 字符?
- r - 在 lapply 中使用 for 循环
- c - 在c中生成随机多个数字
- c++ - 如何在 C++ 中删除目录中的文件?
- javascript - 怎么做才对。(带饼图的年周期)