Update Segmented Progress Bar When CollectionView Index is Changed Swift - swift

Working Example Video
I am trying to create an onboarding view such as Instagram stories with a progress bar on top of the view.
So far I was able to animate to the second or third index in the given time. This animation also changes stack view progress bar. But when I try to scroll to the next or previous collection view index I can not show this action inside the progress bar.
I can read the current page index with page control but can not reflect this reading to progress bar.
class OnboardingViewController: UIViewController, SegmentedProgressBarDelegate {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var stackView: UIStackView!
private var spb: SegmentedProgressBar!
var currentPage = 0
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = slides.count
return pageControl
}()
//Burası Presenter'dan gelecek.
var slides: [OnboardingSlide] = [
OnboardingSlide(title: "Delicious Dishes", image: #imageLiteral(resourceName: "1")),
OnboardingSlide(title: "World-Class Chefs", image: #imageLiteral(resourceName: "2")),
OnboardingSlide(title: "Instant World-Wide Delivery", image: #imageLiteral(resourceName: "3"))
]
override func viewDidLoad() {
super.viewDidLoad()
spb = SegmentedProgressBar(numberOfSegments: slides.count, duration: 3)
spb.frame = CGRect(x: 15, y: 56, width: collectionView.frame.width - 30, height: 4)
spb.delegate = self
spb.topColor = UIColor.white
spb.bottomColor = UIColor.white.withAlphaComponent(0.25)
spb.padding = 2
collectionView.delegate = self
collectionView.dataSource = self
stackView.addArrangedSubview(spb)
spb.startAnimation()
collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
}
func segmentedProgressBarChangedIndex(index: Int) {
updateView(index: index)
}
override var prefersStatusBarHidden: Bool {
return true
}
func segmentedProgressBarFinished() {
print("Finished!")
}
#objc private func tappedView() {
spb.isPaused = !spb.isPaused
}
private func updateView(index: Int) {
print("index: \(index)")
let indexPath = IndexPath(row: index, section: 0)
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
#IBAction func loginButtonTapped(_ sender: UIButton) {
}
#IBAction func signupButtonTapped(_ sender: UIButton) {
}
}
extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
cell.setup(slides[indexPath.row])
return cell
}
}
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.width
currentPage = Int(scrollView.contentOffset.x / width)
pageControl.currentPage = currentPage
updateView(index: currentPage)
print("current page: \(currentPage)")
}
}
I have used
https://github.com/D-32/SegmentedProgressBar
as the segmentedProgressBar
class OnboardingCollectionViewCell: UICollectionViewCell {
static let identifier = String(describing: OnboardingCollectionViewCell.self)
#IBOutlet weak var slideImageView: UIImageView!
#IBOutlet weak var slideTitleLabel: UILabel!
func setup(_ slide: OnboardingSlide) {
slideImageView.image = slide.image
slideTitleLabel.text = slide.title
}
}
struct OnboardingSlide {
let title: String
let image: UIImage
}

extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer .translation(in: view).x > 0 {
spb.rewind()
} else {
spb.skip()
}
}
}
with this, I was able to understand if collection view was scrolled left or right. Thus calling related functions inside the spb does the trick.

Related

How can I update a UICollectionView from another class?

I am trying this for a couple of days now and haven't achieved anything yet. What I am trying to do is when a user picks a User item form the ViewController class, I want to save it in Realm and show it in the CollectionView of the SavedInterestsViewController class. I use a delegate pattern as suggested in this post How to access and refresh a UITableView from another class in Swift, but unfortunately I still receive nil, I guess because the GC removed the collectionView outlet already right? (please correct me if I misunderstood it). However, how can I get this to work by using a delegate pattern? Here is my code, this is the class where the user Picks a new User-item:
protocol ViewControllerDelegate {
func didUpdate(sender: ViewController)
}
class ViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var collectionView: UICollectionView!
var delegate: ViewControllerDelegate?
let numberOfTweets = 5
let realm = try! Realm()
var image = UIImage()
var imageArray: [String] = []
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
searchBar.delegate = self
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("One second...")
let functionClass = NetworkingFunctions()
var loopCount = 0
functionClass.getWikipediaAssumptions(for: searchBar.text!) { [self] (articleArray) in
self.userArray.removeAll()
for x in articleArray {
functionClass.performWikipediaSearch(with: x, language: WikipediaLanguage("en")) { (user) in
self.userArray.append(user)
collectionView.reloadData()
loopCount += 1
}
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if userArray[indexPath.item].checked == false {
userArray[indexPath.item].checked = true
collectionView.reloadData()
let newUser = User()
newUser.image = userArray[indexPath.item].image
newUser.name = userArray[indexPath.item].name
newUser.checked = true
try! realm.write {
realm.add(newUser)
}
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
}
else {
userArray[indexPath.item].checked = false
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
class User: Object {
#objc dynamic var image: NSData = NSData()
#objc dynamic var name: String = ""
#objc dynamic var checked: Bool = false
}
... and this is the class where I want to show the selected item, after the User clicked on the 'Back' Button of the navigation controller of the ViewController class:
class SavedInterestsViewController: UIViewController, ViewControllerDelegate {
func didUpdate(sender: ViewController) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
let realm = try! Realm()
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
fetchDataFromRealm()
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "SavedToNew", sender: self)
}
func fetchDataFromRealm() {
userArray.append(contentsOf: realm.objects(User.self))
collectionView.reloadData()
}
}
extension SavedInterestsViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
}
extension SavedInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
in your code you have lines
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
but it do mostly nothing - you set the delegate to newly created class, didUpdate it - but I don't see any use of it - you don't present it in any way.
If I understand you right - you have SavedInterestsViewController, from it - you open ViewController, do something and when back to SavedInterestsViewController. (I can be wrong with your flow - correct me if so)
In this flow - you have delegate property in ViewController, but it must be of type SavedInterestsViewController. And you have to set it to SavedInterestsViewController when you open ViewController from it. And later in ViewController you have to call didUpdate method of delegate.

My collection view is nil when implicit unwrapping?

I use a UITabBarController to manage the large middle button on the UITabBar. Here is a part of it.
class TabBarController: UITabBarController, UITabBarControllerDelegate, ContentChangedDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupMiddleButton()
}
func setupMiddleButton() {
let tabBarHeight = tabBar.frame.size.height
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: tabBarHeight*1.5, height: tabBarHeight*1.5))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height/2 - tabBarHeight - 8
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.red
menuButton.layer.cornerRadius = menuButtonFrame.height/2
view.addSubview(menuButton)
let largeConfiguration = UIImage.SymbolConfiguration(scale: .large)
let addIcon = UIImage(systemName: "plus", withConfiguration: largeConfiguration)
menuButton.setImage((addIcon), for: .normal)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
#objc private func menuButtonAction(sender: UIButton) {
AddViewController.delegate = self
performSegue(withIdentifier: "addEventSegue", sender: self)
}
}
and I conform another class LifeViewController(I used the class the specify the collecitonView and searchbar and other items in it) to tabBarController but the lifeCollectionView is always nil when implicitly unwrap, Could any one help me, Thank you so much!
class LifeViewController: TabBarController {
let realm = try! Realm()
var reminders : Results<Memorandum>!
let tabBarView = TabBarController()
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet var lifeCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
lifeCollectionView.delegate = self
lifeCollectionView.dataSource = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
self.fetchData()
}
override func reloadCollection() {
if let life = self.lifeCollectionView {
life.reloadData()
} else {
print("life found nil")
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "editing", sender: self)
}
func fetchData() {
reminders = realm.objects(Memorandum.self)
}
}
//MARK: - CollectionView
extension LifeViewController {
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: lifeCollectionView.frame.width/2.1, height: lifeCollectionView.frame.width/2.1)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return reminders.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reminder = reminders[indexPath.item]
let lifeCell = lifeCollectionView.dequeueReusableCell(withReuseIdentifier: "lifeCell", for: indexPath) as! ReminderCell
lifeCell.configureCell(date: reminder.dateReminder, importance: UIColor(hex: reminder.color)!, name: reminder.title, depict: reminder.depiction)
lifeCell.layer.cornerRadius = 12
return lifeCell
}
}
But when I change back to conform the LifeViewController to UIViewController, and other collection view protocols the IBOutlet, delegate and dataSource work again? Why is that?

Populate Collection cell afterwards Swift

I have a mini game in Single-view-app project with item inventory (CollectionView). Its structure in main.Storyboard: CollectionView -> cell -> ContentView -> inventoryImageView. When the game starts items.count of empty cells are generated. Whenever a user taps on imageView of an item he finds, I want this imageView to populate the most left and available cell of the inventory. Something like:
cell.inventoryImageView = itemImageView
How can I access this left unpopulated cell?
The code is:
struct Items {
let imageName: String
var location = (0, 0)
}
var key = Items(imageName: "icons8-key-50")
var chest = Items(imageName: "icons8-closed-treasure-chest-50")
var rock = Items(imageName: "icons8-rock-50")
var bone = Items(imageName: "icons8-human-bone-50")
var mushroom = Items(imageName: "icons8-mushroom-50")
var items = [Items]()
override func viewDidLoad() {
items = [key, chest, rock, bone, mushroom]
}
when user clicks Start button this func gets triggered for every item :
func createItems(imageName: String) {
let imageNamePNG = "\(imageName).png"
let itemImage = UIImage(named: imageNamePNG)
let itemImageView = UIImageView(image: itemImage) itemImageView.frame = CGRect(x: 70, y: 0, width: 63, height: 63)
itemImageView.frame = CGRect(x: Int.random(in: 70...294), y: Int.random(in: 100...543), width: 63, height: 63)
view.addSubview(itemImageView)
createdImages.append(itemImageView)
}
cell creation part:
// MARK: - UICollectionViewDataSource protocol
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell
return cell
}
I don't quite understand what you want to do but I hope this code could help you.
CustomCollectionViewCell.swift
import UIKit
class CustomCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var inventoryImageView: UIImageView!
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var imageButton: UIButton!
var key = Items(imageName: "img-1")
var chest = Items(imageName: "img-2")
var rock = Items(imageName: "img-3")
var bone = Items(imageName: "img-4")
var mushroom = Items(imageName: "img-5")
var items = [Items]()
var index = 0
var createdImages = [Items]()
override func viewDidLoad() {
super.viewDidLoad()
self.items = [key, chest, rock, bone, mushroom]
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
}
#IBAction func imageButtonAction(_ sender: Any) {
index += 1
if index >= items.count{
index = 0
}
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
self.createdImages.append(self.items[index])
self.collectionView.reloadData()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.createdImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.inventoryImageView.image = UIImage(named: self.createdImages[indexPath.item].imageName)
return cell
}
}
Items.swift
struct Items {
let imageName: String
var location = (0, 0)
}

How to expand an xib collectionviewcell height dynamically?

I am looking to make my xib custom collection view cell height dynamic when clicked upon rather than using a fixed variable height.
I have tried using constraints on the heights of the cell in the storyboard.
This is the MotCollectionViewCell.swift code:
import UIKit
protocol ExpandedCellDelegate:NSObjectProtocol{
func topButtonTouched(indexPath:IndexPath)
}
class MotCollectionViewCell: UICollectionViewCell {
#IBOutlet var heightConstraint: NSLayoutConstraint!
#IBOutlet var topButton: UIButton!
weak var delegate:ExpandedCellDelegate?
public var indexPath:IndexPath!
#IBAction func topButtonTouched(_ sender: UIButton) {
if let delegate = self.delegate{
delegate.topButtonTouched(indexPath: indexPath)
}
}
#IBOutlet var testLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
This is the BarChartViewControllerCell.Swift code :
import UIKit
import Charts
class BarChartViewController: UIViewController, ChartViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ExpandedCellDelegate {
// Bar Chart Properties
#IBOutlet var barChartView: BarChartView!
var dataEntry: [BarChartDataEntry] = []
// Chart Data
var result = [String]()
var mileage = [String]()
var colours = [UIColor]()
var list = [Tester]()
// Collection View properties
#IBOutlet var collectionView: UICollectionView!
var expandedCellIdentifier = "MotCollectionViewCell"
var cellWidth:CGFloat{
return collectionView.frame.size.width
}
var expandedHeight : CGFloat = 258
var notExpandedHeight : CGFloat = 75
var dataSource = ["data0","data1","data2","data3","data4"]
var isExpanded = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
isExpanded = Array(repeating: false, count: dataSource.count)
//Register nib cell
let nibCell = UINib(nibName: expandedCellIdentifier, bundle: nil)
collectionView.register(nibCell, forCellWithReuseIdentifier: expandedCellIdentifier)
}
// Collection View functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: expandedCellIdentifier, for: indexPath) as! MotCollectionViewCell
cell.indexPath = indexPath
cell.delegate = self
//configure Cell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if isExpanded[indexPath.row] == true{
return CGSize(width: cellWidth, height: expandedHeight)
}else{
return CGSize(width: cellWidth, height: notExpandedHeight)
}
}
func topButtonTouched(indexPath: IndexPath) {
isExpanded[indexPath.row] = !isExpanded[indexPath.row]
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.collectionView.reloadItems(at: [indexPath])
}, completion: { success in
print("success")
})
}
}
When the cell is clicked, the cell expands to the height which I declared as a constant, what I am trying to achieve is have the cell expand according to the data within it.

how can we use tapGesture for playing videos in Tvos

How can we use TapGesture in uicollectionview for playing videos in tvos. When we click the First Image, it should load the appropriate video for that when we tap and so on. How can I do this when the videos are in local ?
import Foundation
import UIKit
class FirstViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate {
let reuseIdentifierFeatured = "FeaturedCell"
var PosterImage : UIImage!
var ImagesDisplay = [String]()
var Try = [AppletvCollectionViewCell]()
var DefaultSize = CGSizeMake(267, 153)
var FocusSize = CGSizeMake(294, 268)
#IBOutlet weak var PosterBackGroundDisplay: UIImageView!
#IBOutlet weak var ScrollView: UIScrollView!
#IBOutlet weak var CollectionView1: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
ImagesDisplay = ["Slow motion fire video Screenshot-1.jpg","Slow motion fire video Screenshot-2.jpg","Slow motion fire video Screenshot-3.jpg","Slow motion fire video Screenshot-4.jpg","Slow motion fire video Screenshot-5.jpg","Sun Timelapse Screenshot 1.jpg","Sun Timelapse Screenshot 2.jpg"]
self.CollectionView1.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
self.ScrollView!.contentSize = CGSizeMake(1920, 239)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 50
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 50
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0.0, left: 40.0, bottom: 0.0, right: 50.0)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return ImagesDisplay.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell : AppletvCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! AppletvCollectionViewCell {
cell.Poster.image = UIImage(named: ImagesDisplay[indexPath.row])
if cell.gestureRecognizers?.count == nil {
let tap = UITapGestureRecognizer(target: self, action: "Tapped:")
tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
cell.addGestureRecognizer(tap)
}
return cell
}else {
return AppletvCollectionViewCell()
}
}
func Tapped(gesture : UIGestureRecognizer) {
print("TappedSucess")
let playerVC = PlayerViewController()
playerVC.playVideo()
[self.presentViewController(playerVC, animated: true, completion: nil)]
}
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let prev = context.previouslyFocusedView as? AppletvCollectionViewCell {
UIView.animateWithDuration(0.1, animations: { () -> Void in
prev.Poster.frame.size = self.DefaultSize
})
}
if let next = context.nextFocusedView as? AppletvCollectionViewCell {
UIView.animateWithDuration(0.1, animations: { () -> Void in
next.Poster.frame.size = self.FocusSize
self.PosterBackGroundDisplay.image = next.Poster.image
})
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let playerVC = PlayerViewController()
playerVC.playVideo()
[self.presentViewController(playerVC, animated: true, completion: nil)]
}}
You can use the given method to load and play video.
func loadAndPlayVideo()
{
if let path = NSBundle.mainBundle().pathForResource("LocalFilename", ofType:"mp4")
{
let url = NSURL(fileURLWithPath:path)
let playerItem = AVPlayerItem(URL: url)
let player = AVPlayer(playerItem: playerItem);
let playerVC = AVPlayerViewController()
playerVC.player = player
self.presentViewController(playerVC, animated: true, completion:nil)
playerVC.player?.play()
}
}
If you want to play multiple video in the same player then use method "replaceCurrentItemWithPlayerItem".
Refer this link for more info-
https://iosguy.com/2012/01/11/multiple-video-playback-on-ios/