【问题标题】:CollectionView FlowLayout overlapping when scrolling not working滚动时 CollectionView FlowLayout 重叠不起作用
【发布时间】:2021-07-09 06:16:53
【问题描述】:

希望你们一切顺利

在这里我创建了一个集合视图流布局,一些场景不起作用,请分享您的参考。 这是集合视图

    import UIKit
    class ViewController: UIViewController {
        
        @IBOutlet weak var collection: UICollectionView!
        private let kCellHeight: CGFloat = UIScreen.main.bounds.width/2+38
        private let kItemSpace: CGFloat = UIScreen.main.bounds.width/2.08
        lazy var expand_click = false
        lazy var index_value = [String]()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            collection.delegate = self
            collection.dataSource = self
            let layout = StickyCollectionViewFlowLayout2()
            layout.minimumLineSpacing = -kItemSpace
            collection.collectionViewLayout = layout
            collection.reloadData()
        }
    }
    
    extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 15
        }    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
            print("Index",indexPath.row)
            return cell
        }
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: view.frame.width-40, height: kCellHeight)
        }
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            if (15)-1 == indexPath.row {
                self.showAlert(alertText: "", alertMessage: "last Cell")
            }else{
                if index_value.contains("\(indexPath.row)") {
                    self.showAlert(alertText: "", alertMessage: "Redirect")
                    expand_click = true
                }else{
                    index_value.removeAll()
                    index_value.append("\(indexPath.row)")
                    expand_click = true
                    cellData = indexPath.row
                    collectionView.performBatchUpdates({
                    }, completion: nil)
                }
            }
        }
    }

集合视图单元格

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var container: UIView!
   
    override func layoutSubviews() {
        container.backgroundColor = .white
        container.layer.cornerRadius = 13
        container.layer.shadowRadius = 2
        container.layer.shadowOpacity = 0.7
        container.layer.shadowOffset = CGSize(width: 0, height: 1)
        container.layer.shadowColor = UIColor.black.withAlphaComponent(0.45).cgColor
    }    
}
  • 单击单元格时,它将展开单元格并移动到其他单元格下方 > * 展开的单元格再次单击它将被重定向到另一个页面 forEx(我显示警报) > *最后一个单元格点击它也应该重定向这些都是我自己做的,如果我们有15张卡片,它可以正常工作超过50张卡片 > 滚动不流畅,我们有一个争用大小的问题,也许我 > 无法解决问题
**Collection view FlowLayout**


class StickyCollectionViewFlowLayout2: UICollectionViewFlowLayout {
    
    var firstItemTransform: CGFloat?
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let items = NSArray (array: super.layoutAttributesForElements(in: rect)!, copyItems: true)
        
        print("------------------------------------------------------------------------------------------------------------------------")
        print("Count-------->",items.count,"<--------Count")
        print("------------------------------------------------------------------------------------------------------------------------")
        
        
        var headerAttributes: UICollectionViewLayoutAttributes?
        
        self.firstItemTransform = nil
        if cellData != nil {
            let min = cellData!
            print(min)
            var b = [UICollectionViewLayoutAttributes?]()
            var a = false
            items.forEach({ (object) in
                let object  = object as! UICollectionViewLayoutAttributes
                if min == object.indexPath.row {
                    a = true
                }else{
                    if a == true {
                        b.append(object)
                    }
                }
            })
            for attributes in b {
                if attributes?.representedElementKind == UICollectionView.elementKindSectionHeader {
                    headerAttributes = attributes
                }
                else {
                    self.atributeLayout(attributes!, headerAttributes: headerAttributes)
                }
            }
            cellData = nil
        }else{
            items.enumerateObjects(using: { (object, idex, stop) -> Void in
                let attributes = object as! UICollectionViewLayoutAttributes
                
                if attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
                    headerAttributes = attributes
                }
                else {
                    self.atributeLayoutReset(attributes, headerAttributes: headerAttributes)
                }
            })
        }
        return items as? [UICollectionViewLayoutAttributes]
    }
    
    func atributeLayout(_ attributes: UICollectionViewLayoutAttributes, headerAttributes: UICollectionViewLayoutAttributes?){
        let minY = self.collectionView!.bounds.minY + self.collectionView!.contentInset.top
        var maxY = attributes.frame.origin.y+attributes.frame.height/2+80
        if let headerAttributes = headerAttributes {
            maxY -= headerAttributes.bounds.height
        }
        let finalY = max(minY, maxY)
        var origin = attributes.frame.origin
        let deltaY = (finalY - origin.y) / attributes.frame.height + 100
        
        if let itemTransform = self.firstItemTransform {
            let scale = 1 - deltaY * itemTransform
            attributes.transform = CGAffineTransform(scaleX: scale, y: scale)
        }
        origin.y = finalY
        attributes.frame = CGRect(origin: origin, size: attributes.frame.size)
        attributes.zIndex = attributes.indexPath.row
    }
    func atributeLayoutReset(_ attributes: UICollectionViewLayoutAttributes, headerAttributes: UICollectionViewLayoutAttributes?){
        cellIndex = nil
        if isExpandCell != true  {
            let minY = self.collectionView!.bounds.minY + self.collectionView!.contentInset.top
            var maxY = attributes.frame.origin.y
            if let headerAttributes = headerAttributes {
                maxY -= headerAttributes.bounds.height
            }
            let finalY = max(minY, maxY)
            var origin = attributes.frame.origin
            let deltaY = (finalY - origin.y) / attributes.frame.height + 100
            if let itemTransform = self.firstItemTransform {
                let scale = 1 - deltaY * itemTransform
                attributes.transform = CGAffineTransform(scaleX: scale, y: scale)
            }
            origin.y = finalY
            attributes.frame = CGRect(origin: origin, size: attributes.frame.size)
            attributes.zIndex = attributes.indexPath.row
            //            })
        }else{
            print(collectionView!.contentInset.top,collectionView!.bounds.minY)
            let minY = 0.0 + collectionView!.contentInset.top
            var maxY = attributes.frame.origin.y
            if let headerAttributes = headerAttributes {
                maxY -= headerAttributes.bounds.height
            }
            let finalY = max(minY, maxY)
            var origin = attributes.frame.origin
            let deltaY = (finalY - origin.y) / attributes.frame.height + 100
            if let itemTransform = firstItemTransform {
                let scale = 1 - deltaY * itemTransform
                attributes.transform = CGAffineTransform(scaleX: scale, y: scale)
            }
            origin.y = finalY
            attributes.frame = CGRect(origin: origin, size: attributes.frame.size)
            attributes.zIndex = attributes.indexPath.row
        }
    }
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return false
    }
}

如果有人体验过收藏视图,请分享您的参考资料 谢谢

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


    【解决方案1】:

    您好,请尝试我的代码。我在 iPhone 模拟器上测试过,效果很好。

    import SwiftUI
    
    struct CardView: View {
        
        static let CARD_HEIGHT: CGFloat = 200
        static let CARD_WIDTH: CGFloat = 300
        static let TAB_HEIGHT: CGFloat = 30
        
        @State var selected: Int? = nil
        let cards: Int
        
        var body: some View {
            ScrollView {
                ZStack(alignment: .top) {
                    ForEach(0 ..< cards) { card_i in
                        Button {
                            withAnimation {
                                self.selected = self.selected == card_i ? nil : card_i
                            }
                            print("A card was tapped. Do something with card_i here")
                        } label: { self.card }
                        .buttonStyle(PlainButtonStyle())
                        .frame(width: Self.CARD_WIDTH, height: Self.CARD_HEIGHT, alignment: .top)
                        .offset(x: .zero, y: CGFloat(card_i) * Self.TAB_HEIGHT + ((selected ?? cards + 1) < card_i ? Self.CARD_HEIGHT - Self.TAB_HEIGHT / 2 : 0))
                    }
                }
                .frame(height: Self.CARD_HEIGHT + Self.TAB_HEIGHT * CGFloat(cards), alignment: .top)
                .padding()
            }
                
        }
        
        var card: some View {
            RoundedRectangle(cornerRadius: 17, style: .continuous)
                .fill(Color.gray)
                .overlay(RoundedRectangle(cornerRadius: 17, style: .continuous).stroke(Color.black, lineWidth: 5))
        }
    }
    
    

    编辑

    这样使用

    let swiftUIview = CardView(cards: 10, onCardTapped: { card in 
        print("card number \(card) tapped")
    })
    
    let uiViewController = UIHostingController(rootView: swiftUIview)
    

    Gif 因过时而被删除。

    【讨论】:

    • 感谢分享,太棒了。我怎样才能在swift中实现
    • 谢谢!这是 Swift 代码。要在 UIKit 中使用,请使用我提供的 UIHostingController 代码。或参考this page。另请参阅编辑后的代码。
    • 超过 100 张卡片时如何移除顶部空间和滚动不起作用
    • @ManikandanS 我已经更改了代码并修复了所有这些问题。即使有 100 多张卡片,滚动也能完美运行。而且顶部没有更多空间。请复制更新后的代码并尝试一下。
    • @ManikandanS 当然!如果这解决了您的问题,也许您会考虑将其标记为已接受并授予赏金?
    【解决方案2】:

    我添加了类似这样的内容,但我需要扩展 collectionView

    class collect: UICollectionViewFlowLayout {
        override func prepare() {
            super.prepare()
            self.minimumLineSpacing = -UIScreen.main.bounds.width/2.08
        }
        
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            let layoutAttributes = super.layoutAttributesForElements(in: rect)
            for currentLayoutAttributes in layoutAttributes! {
                currentLayoutAttributes.zIndex = currentLayoutAttributes.indexPath.row;
            }
            return layoutAttributes;
        }
    }
    

    【讨论】:

    • 如何扩展收藏?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多