簡體   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