美文网首页swift学习
iOS UICollectionView、UITableView

iOS UICollectionView、UITableView

作者: gaookey | 来源:发表于2021-04-08 20:10 被阅读0次
    import UIKit
    
    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
        
        let headerViewHeight: CGFloat = 500
        
        private lazy var headerView: UIView = {
            let view = UIView(frame: CGRect(x: 0, y: -headerViewHeight, width: UIScreen.main.bounds.width, height: headerViewHeight))
            view.clipsToBounds = true
            return view
        }()
        
        private lazy var imageView: UIImageView = {
            let view = UIImageView(image: UIImage(named: "image"))
            view.frame = headerView.bounds
            return view
        }()
        
        private lazy var collectionView: UICollectionView = {
            let view = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: UICollectionViewFlowLayout())
            view.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
            view.delegate = self
            view.dataSource = self
            view.contentInset = UIEdgeInsets(top: headerViewHeight, left: 0, bottom: 0, right: 0)
            view.backgroundColor = .white
            view.contentInsetAdjustmentBehavior = .never
            return view
        }()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            view.addSubview(collectionView)
            collectionView.addSubview(headerView)
            headerView.addSubview(imageView)
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            let offset = scrollView.contentOffset.y
            
            // 重新赋值,防止用力拖拽时的回弹
            imageView.frame.origin.y = 0
            if (offset >= -headerViewHeight && offset <= headerViewHeight) {
                imageView.frame.origin.y = (offset + headerViewHeight) * 0.5
            }
        }
        
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 600
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
            cell.backgroundColor = UIColor(red: CGFloat(arc4random() % 256) / 255.0, green: CGFloat(arc4random() % 256) / 255.0, blue: CGFloat(arc4random() % 256) / 255.0, alpha: 1.0)
            return cell
        }
    }
    

    相关文章

      网友评论

        本文标题:iOS UICollectionView、UITableView

        本文链接:https://www.haomeiwen.com/subject/udnvkltx.html