繁体   English   中英

在collectionView swift ios中选择和取消选择

[英]Select and Deselect in collectionView swift ios

我正在处理collectionView并坚持下去,就像当用户点击collectionView单元格项目时它会相应地改变颜色并且其他项目颜色也会改变。第一个单元格项目将处于活动状态并且颜色将为蓝色并且其他单元格颜色将被停用并且颜色为灰色.但在我的情况下,代码无法正常工作,请参阅下面的代码。

var category: [Category] = [
        Category(cat: "For You"),
        Category(cat: "Top chats"),
        Category(cat: "Kids"),
        Category(cat: "Categories"),
        Category(cat: "Editor Choice")
    ]
    
    var isSelected: Int? = nil {
        didSet {
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    }
extension DashboardViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.isSelected = indexPath.row
    }
}

extension DashboardViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return category.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        configureDashboardCell(collectionView, cellForItemAt: indexPath)
    }
    
    func configureDashboardCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CategoryCell.self), for: indexPath) as? CategoryCell else {return UICollectionViewCell()}
        cell.lblName.text = category[indexPath.item].cat
        
        if self.isSelected == indexPath.row {
            let textColor: UIColor = .blue
            let underLineColor: UIColor = .blue
            let underLineStyle = NSUnderlineStyle.single.rawValue
            
            let labelAtributes:[NSMutableAttributedString.Key : Any] = [
                NSAttributedString.Key.foregroundColor: textColor,
                NSAttributedString.Key.underlineStyle: underLineStyle,
                NSAttributedString.Key.underlineColor: underLineColor
            ]
            let underlineAttributedString = NSAttributedString(string: cell.lblName.text ?? "",
                                                        attributes: labelAtributes)
            cell.lblName.attributedText = underlineAttributedString
        } else {
            let textColor: UIColor = .gray
            let labelAtributes:[NSMutableAttributedString.Key : Any] = [
                NSAttributedString.Key.foregroundColor: textColor
            ]
            let underlineAttributedString = NSAttributedString(string: cell.lblName.text ?? "",
                                                attributes: labelAtributes)
            cell.lblName.attributedText = underlineAttributedString
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (self.collectionView.bounds.width / 3) - 5 , height: 40)
    }
}

在我看来,我建议您使用isSelected属性来控制所有样式。

// Cells become highlighted when the user touches them. 
// The selected state is toggled when the user lifts up from a highlighted cell.
// Override these methods to provide custom UI for a selected or highlighted state.
// The collection view may call the setters inside an animation block.

open var isSelected: 布尔


你应该把所有的任务放到cell中,而不是通过collectionView直接控制它。

正如你上面提到的,

第一个单元格项目将处于活动状态,颜色将为蓝色,其他单元格颜色将停用,颜色为灰色

所以你只想要两个状态, selecteddeselected ,一个只选择。

让我们尝试一下collection.selectItem(at: <#T##IndexPath?#>, animated: <#T##Bool#>, scrollPosition: <#T##UICollectionView.ScrollPosition#>) ,它会调用单元格isSelected两次用于新选定的单元格和需要取消选择的旧单元格。

请在willDisplayCell中使用您的选择。 首先让单元格出现在cellForRowAt的视图中,然后尝试根据需要重新设计单元格。

func configureDashboardCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CategoryCell.self), for: indexPath) as? CategoryCell else {return UICollectionViewCell()}
        cell.lblName.text = category[indexPath.item].cat
        let textColor: UIColor = .gray
            let labelAtributes:[NSMutableAttributedString.Key : Any] = [
                NSAttributedString.Key.foregroundColor: textColor
            ]
            let underlineAttributedString = NSAttributedString(string: cell.lblName.text ?? "",
                                                attributes: labelAtributes)
            cell.lblName.attributedText = underlineAttributedString
        return cell
    }

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if self.isSelected == indexPath.row {
            let textColor: UIColor = .blue
            let underLineColor: UIColor = .blue
            let underLineStyle = NSUnderlineStyle.single.rawValue
            
            let labelAtributes:[NSMutableAttributedString.Key : Any] = [
                NSAttributedString.Key.foregroundColor: textColor,
                NSAttributedString.Key.underlineStyle: underLineStyle,
                NSAttributedString.Key.underlineColor: underLineColor
            ]
            let underlineAttributedString = NSAttributedString(string: cell.lblName.text ?? "",
                                                        attributes: labelAtributes)
            cell.lblName.attributedText = underlineAttributedString
        } 

}

并在点击单元格时重新加载数据

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.isSelected = indexPath.row
        collectionView.reloadData()
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM