Как получить доступ к членам ячейки (для анимации) из метода scrollViewDidScroll в UICollectionViewController? - PullRequest
0 голосов
/ 08 октября 2019

Как получить доступ к элементам (UIImage или UITextView), добавленным к представлению в UICollectionViewCell из метода scrollViewDidScroll в UICollectionViewController?

Я хотел бы анимировать, т.е. перемещать изображение и текст с "различной скоростью""при прокрутке по вертикали до следующей ячейки.

Я понимаю, что это можно сделать с помощью метода scrollViewDidScroll, но я не знаю, как получить доступ к членам.

ViewController:

class OnboardingViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
     **code here which I just can't figure out....**
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = .white
        collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
        collectionView?.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false

        // this method "creates" the UIPageControll and assigns  
        setupPageControl()
    }

    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.currentPage     = 0
        pageControl.numberOfPages   = data.count <--- data provided by a model from a plist - works perfectly
        pageControl.currentPageIndicatorTintColor   = .black
        pageControl.pageIndicatorTintColor          = .gray
        pageControl.translatesAutoresizingMaskIntoConstraints  = false

        return pageControl
    }()

    private func setupPageControl() {
        view.addSubview(pageControl)
        NSLayoutConstraint.activate([
            onboardingPageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            onboardingPageControl.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
            onboardingPageControl.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
        ])
    }

все остальные методы переопределения реализованы в расширении и работают нормально, т.е.

numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

Это PageCell:

class PageCell: UICollectionViewCell {

    var myPage: MyModel? {
        didSet {
            guard let unwrappedPage = myPage else { return }

            // the image in question:
            myImage.image = UIImage(named: unwrappedPage.imageName)
            myImage.translatesAutoresizingMaskIntoConstraints = false
            myImage.contentMode   = .scaleAspectFit

            // the text in question
            let attributedText = NSMutableAttributedString(string: unwrappedPage.title, attributes: [:])
            attributedText.append(NSAttributedString(string: "\n\(unwrappedPage.description)", attributes: [:]))
            myText.attributedText = attributedText
            myText.translatesAutoresizingMaskIntoConstraints    = false
            myText.textColor                                    = .black
            myText.textAlignment                                = .center
            myText.isEditable                                   = false
            myText.isScrollEnabled                              = false
            myText.isSelectable                                 = false
    }

    let myImage: UIImageView = {
        let imageView           = UIImageView()
        return imageView
    }()

    let myText: UITextView = {
        let textView    = UITextView()
        return textView
    }()

    fileprivate func setup() {
        addSubview(myImage)
        NSLayoutConstraint.activate([
            myImage.safeAreaLayoutGuide.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 60),
            myImage.centerXAnchor.constraint(equalTo: centerXAnchor),
            myImage.leadingAnchor.constraint(equalTo: leadingAnchor),
            myImage.trailingAnchor.constraint(equalTo: trailingAnchor),
            myImage.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4)
        ])

        addSubview(myText)
        NSLayoutConstraint.activate([
            myText.topAnchor.constraint(equalTo: myImage.bottomAnchor, constant: 16),
            myText.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            myText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16)
        ])
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

1 Ответ

0 голосов
/ 08 октября 2019

Вы можете достичь этого, получив текущие видимые ячейки вашего collectionView , и было бы здорово, если бы вы получили к ним доступ в scrollViewDidEndDecelerating intead of scrollViewDidScroll .

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        for cell in collectionView.visibleCells {
          //cell.imageView 
          //cell.txtView
         // you can access both imageView and txtView here

        let indexPath = collectionView.indexPath(for: cell)
        print(indexPath) // this will give you indexPath as well to differentiate
        }
 }
...