2017-02-16 13 views
1

Я разрабатываю простое коммерческое приложение в iPhone с помощью Swift 3, и я новичок в разработке. У меня есть ViewController с UIView, который обрабатывает изображения с помощью UIPageControl. У меня также есть метки и горизонтальные прокрутки UICollectionViews в том же ViewController. Я настроил свой scrollview с помощью Storyboard и настроил код UIPageControl в коде.Как отображать слайды изображений UIView и CollectionViews в двух пользовательских TableViewCells?

Проблема: когда я ввел прокрутку в ViewController, UIPageControl и CollectionViewCells остаются в том же положении.

У меня есть образец здесь. Пожалуйста, см. Изображение для лучшего понимания: Image showing my ViewController where the PageControl stays same while the View is scrolled и другое изображение ViewController while scrolling up.

Итак, я обнаружил, что scrollview сталкивается со свитками CollectionView и PageControl.

Может кто-нибудь рассказать мне, как я могу вставлять свой UIView для скользящих изображений в пользовательский TableViewCell и остальную часть моего CollectionViews в другой пользовательский TableViewCell, чтобы включить вертикальную прокрутку?

Вот мой ViewController.swift:

import UIKit 
class Home: UIViewController{ 
    @IBOutlet var myView: UIView!  
    @IBOutlet var pageControl: UIPageControl! 

    override func viewDidLoad() { 
     super.viewDidLoad()    
     self.addSlideMenuButton() 
     self.title="Home" 
     //Image Loop 
     self.pageControl.currentPage = -1 
     configurePageControl() 
     slide = -1 
     self.changeSlide() 
     var timer = Timer.scheduledTimer(timeInterval: 10 
      , target: self, selector: #selector(changeSlide), userInfo: nil, repeats: true);   

     myView.isUserInteractionEnabled = true 
     let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swiped(_gesture:))) 

     swipeRight.direction = UISwipeGestureRecognizerDirection.right 
     myView.addGestureRecognizer(swipeRight) 

     let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_gesture:))) 
     swipeLeft.direction = UISwipeGestureRecognizerDirection.left 
     myView.addGestureRecognizer(swipeLeft)   

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    var images = [UIImage(named:"banner2"),UIImage(named:"banner1"),UIImage(named:"banner3"),UIImage(named:"banner4"),UIImage(named:"banner5")]  

    var slide:Int = 0   
    func changeSlide(){ 

     var loop : UIImageView!    
     loop = UIImageView(frame: myView.bounds) 
     loop.contentMode = UIViewContentMode.scaleToFill   

     if(slide == images.count-1) 
     { 
      slide=0 
      loop.image = images[slide] 
      self.pageControl.currentPage=slide 
     } 
     else 
     { 
      slide+=1 
      loop.image = images[slide] 
      self.pageControl.currentPage=slide 
     } 
      loop.layer.affineTransform() 
     myView.addSubview(loop)    
    } 


    @IBAction func pageChange(_ sender: AnyObject) {   
    } 

    func swiped(_gesture: UIGestureRecognizer) { 

     var loop : UIImageView! 
     loop = UIImageView(frame: myView.bounds) 
     loop.contentMode = UIViewContentMode.scaleToFill 
     loop.image = images[slide] 
     myView.addSubview(loop) 

     if let swipeGesture = _gesture as? UISwipeGestureRecognizer { 

      switch swipeGesture.direction { 

      case UISwipeGestureRecognizerDirection.right : 

       // decrease index first 
       // check if index is in range 

       if (slide == 0) { 

        slide = images.count-1 
        loop.image = images[slide] 
        self.pageControl.currentPage = slide 
       } 

       else 
       { 

        slide-=1 
        loop.image = images[slide] 
        self.pageControl.currentPage = slide 

       } 

      case UISwipeGestureRecognizerDirection.left: 


       // increase index first 
       // check if index is in range 

       if (slide == images.count-1) { 

        slide = 0 
        loop.image = images[slide] 
        self.pageControl.currentPage = slide 
       } 
       else{ 
        slide+=1 
        loop.image = images[slide] 
        self.pageControl.currentPage = slide 
       }     
      default: 
       break //stops the code/codes nothing. 

      } 
     } 

    } 

    func configurePageControl() { 
     self.pageControl.numberOfPages = images.count 
     self.pageControl.currentPage = slide 
     self.pageControl.tintColor = UIColor.red 
     self.pageControl.pageIndicatorTintColor = UIColor.gray 
     self.pageControl.currentPageIndicatorTintColor = UIColor.green 

     self.myView.addSubview(pageControl) 

     self.view.addSubview(pageControl) 
    }   
} 

Этот документ содержит код для UIView контура изображения и UIPageControl также с возможностью перелистывать изображения.

Может кто-то, пожалуйста, помогите мне? Заранее спасибо.

ответ

1

** Вот как я это сделал: ** Шаг 1: - Сначала вам нужно создать пользовательскую ячейку. Вот код для пользовательской ячейки:

class MovieCollectionViewCell: UICollectionViewCell { 

var moviePoster = UIImageView() 
var view: UIView = UIView() 
override init(frame: CGRect) { 
    super.init(frame: frame) 

    contentView.addSubview(moviePoster) 
    moviePoster.contentMode = .scaleAspectFill 
    moviePoster.translatesAutoresizingMaskIntoConstraints = false 

    let constraints : [NSLayoutConstraint] = [ 

     moviePoster.topAnchor.constraint(equalTo: contentView.topAnchor), 
     moviePoster.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), 
     moviePoster.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), 
     moviePoster.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) 
    ] 
    NSLayoutConstraint.activate(constraints) 
} 

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

Это установит ваше изображение в режим просмотра изображений. Я использовал якоря согласно swift 3.

Шаг 2: - Создать таблицуView, в которой swipeView - это представление, которое будет установлено в headerView таблицыView. Добавить collectionView в swipeView в качестве подзапроса. После этого установите swapView в headerView таблицыView и выполните настройки pageControl. Вот код:

var tableView : UITableView = UITableView(
    frame: CGRect.zero, 
    style: .grouped 
) 
var swipeView : UIView = UIView() 
var myCollectionView: UICollectionView! 
var indicator = MyIndicator() 
var pageControl : UIPageControl = UIPageControl() 
var detailsViewVM : DetailsViewViewModel! 

override func viewDidLoad() { 
    super.viewDidLoad() 


    self.view.backgroundColor = UIColor.white 
    self.view.addSubview(self.tableView) 

    self.tableView.rowHeight = UITableViewAutomaticDimension 
    self.tableView.estimatedRowHeight = 44 
    self.tableView.dataSource = self 
    self.tableView.delegate = self 
    self.tableView.register(
     DetailsCustomTableViewCell.self, 
     forCellReuseIdentifier: "textCell" 
    ) 
    self.tableView.register(
     StarRatingCell.self, 
     forCellReuseIdentifier: "starRatingCell" 
    ) 
    self.tableView.translatesAutoresizingMaskIntoConstraints = false 
// self.tableView.backgroundColor = UIColor(netHex: 0x90caf9) 
    self.view.addSubview(self.tableView) 

    let tableViewConstraints : [NSLayoutConstraint] = [ 
     self.tableView.topAnchor.constraint(equalTo: view.topAnchor), 
     self.tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), 
     self.tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), 
     self.tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) 
    ] 
    NSLayoutConstraint.activate(tableViewConstraints) 

// MARK : Collection view layout 

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
    layout.scrollDirection = .horizontal 

    self.myCollectionView = UICollectionView(
     frame: CGRect(
      x: 0, 
      y: 0, 
      width: self.view.bounds.width, 
      height: 200), 
     collectionViewLayout: layout 
    ) 

    self.myCollectionView.isPagingEnabled = true 
    self.myCollectionView.dataSource = self 
    self.myCollectionView.delegate = self 

    self.myCollectionView.register(
     MovieCollectionViewCell.self, 
     forCellWithReuseIdentifier: "MyCell" 
    ) 
    self.swipeView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200)) 
    self.myCollectionView.backgroundColor = UIColor.gray 
    indicator.StartActivityIndicator(obj: self.myCollectionView) 
    self.swipeView.addSubview(myCollectionView) 
    self.tableView.tableHeaderView = self.swipeView 

// MARK : UIPageControl 

    configurePageControl() 
    self.pageControl.translatesAutoresizingMaskIntoConstraints = false 
    self.pageControl.bottomAnchor.constraint(equalTo: swipeView.bottomAnchor, constant : 8).isActive = true 
    self.pageControl.centerXAnchor.constraint(equalTo: swipeView.centerXAnchor).isActive = true 
    self.pageControl.heightAnchor.constraint(equalToConstant: 44).isActive = true 
    self.pageControl.leadingAnchor.constraint(equalTo: self.swipeView.leadingAnchor).isActive = true 
    self.pageControl.trailingAnchor.constraint(equalTo: self.swipeView.trailingAnchor).isActive = true 

} 

func configurePageControl() { 
     self.pageControl.currentPage = 0 
     self.pageControl.pageIndicatorTintColor = UIColor(netHex : 0xd6eaf8) 
     self.pageControl.currentPageIndicatorTintColor = UIColor(netHex: 0xd81b60) 
     self.swipeView.addSubview(pageControl) 
     swipeView.bringSubview(toFront: pageControl) 
    } 

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { 
    let x = myCollectionView.contentOffset.x 
    let w = myCollectionView.bounds.size.width 
    self.pageControl.currentPage = Int(ceil(x/w)) 
} 

func reloadView() { 
    self.pageControl.numberOfPages = self.detailsViewVM.getMoviePosterArray().count 
    self.myCollectionView.reloadData() 
    indicator.StopActivityIndicator() 
} 

extension DetailsViewController: UICollectionViewDelegateFlowLayout { 

func collectionView(_ collectionView: UICollectionView, 
        layout collectionViewLayout: UICollectionViewLayout, 
        minimumLineSpacingForSectionAt section: Int) -> CGFloat 
{ 

    return 0.0 
} 

    func collectionView(_ collectionView: UICollectionView, 
         layout collectionViewLayout: UICollectionViewLayout, 
         sizeForItemAt indexPath: IndexPath) -> CGSize 
    { 

     return CGSize(width: self.view.bounds.width, height: self.myCollectionView.bounds.height) 
    } 
} 

Надеюсь, что этот ответ решит вашу проблему.

+0

Эй спасибо за ответ. Да, ваш ответ помогает. Однако я новичок в этом и сомневаюсь. Что такое MyIndicator и DetailsViewViewModel! и зачем использовать его? Также не могли бы вы разместить полный код для моего лучшего понимания? Особенно TableViewCell класс кода также для textCell и starRatingCell. –

+0

txtCell - это текстовая ячейка в остальной части таблицыView и starRatingCell - это ячейка рейтинга для моего приложения для фильмов. Ячейка txtCell такая же, как и MovieCollectionViewCell, только разница в том, что ее tableViewCell и вместо UIImageView есть UIlabel. Для ознакомления с кодом [мой предстоящий проект фильмов] (https://github.com/PravinNagargoje/movies) –