首页 > 解决方案 > 自定义图像和开关未在正确位置的集合视图控制器中显示

问题描述

我的要求是,我需要在集合视图控制器中填充 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 电池时,这两个电池也出现在其他电池中。

我没有得到,我犯了什么错误。为了更好地理解我的要求,我分享了一张图片。 在此处输入图像描述

标签: iosswiftuicollectionview

解决方案


推荐阅读