AVPlayer not play - swift4

I have UICollectionView and UICollectionViewCell
I created AVPlayer in IUCollectionViewCell
When I click on the cell print AVPlayer Play but AVPlayer not play.
UICollectionView Cell ;
class UserProfilePhotoCell: UICollectionViewCell {
var avPlayer: AVPlayer?
var avPlayerViewConroller: AVPlayerViewController?
var avPlayerLayer: AVPlayerLayer?
var avPlayerItem: AVPlayerItem?
var player2: AVPlayer?
var post: ProfileVideo? {
didSet{
print(post?.videoPath)
let url = NSURL(string: (post?.videoPath)!)
player2 = AVPlayer(url: url! as URL)
let playerLayer = AVPlayerLayer(player: player2)
playerLayer.frame = bounds
playerLayer.videoGravity = .resizeAspect
self.layer.addSublayer(playerLayer)
}
}
func baslat(){
player2?.play()
print("AVPlayer Play")
}
func durdur(){
player2?.pause()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
CollectionView;
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! UserProfilePhotoCell
cell.baslat()
}

Related

How to update a UICollectionViewCell Label?

I am trying to change a text label in a UICollectionViewCell, but for some reason it just will not update. Any help would be aprreciated. Thanks!
You can use didSet to make your code a bit reactive.
class CollectionViewCell : UICollectionViewCell{
var text = "" {
didSet{
self.label.text = text
}
}
private var label : UILabel = {
let label = UILabel()
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CollectionViewClass : UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
var collectionView = UICollectionView()
let id = "cell ID"
override func viewDidLoad() {
super.viewDidLoad()
collectionView = UICollectionView(frame: self.view.frame)
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: id)
collectionView.dataSource = self
collectionView.delegate = self
self.view.addSubview(collectionView)
collectionView.backgroundColor = .white
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! CollectionViewCell
cell.text = "some text"
cell.backgroundColor = .red
return cell
}
}
In the above code, cell's text value is given everytime it's loaded. Whenever text is set, didset is called which updates the label value.

UICollectionView not populating from Array with data

I have an array of 115 objects containing name and photo url string from Firebase. Printing the data shows results so i know its pulling data correctly.
The problem is the Cells are never populated by the data.
If i add a print(name) inside the class DJProfileCell: UICollectionViewCell it never gets called so i believe thats where the issue is.
class VLCDJProfileViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var similarArtistsCollection: UICollectionView!
var ref: DatabaseReference!
let profileCellID = "cellId"
var djObject = SimilarDJ(image: "image1", name: "name1")
var djsSimilarArray = [SimilarDJ]()
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
loadDJs()
collectionView?.register(DJProfileCell.self, forCellWithReuseIdentifier: profileCellID)
}
func loadDJs(){
let allDJs = self.ref.child("DJ")
allDJs.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let djsDict = snap.value as! [String: Any]
let PhotoUrl = djsDict["PhotoUrl"] as! String
let name = djsDict["name"] as! String + " "
self.djObject = SimilarDJ (image: PhotoUrl, name: name + " ")
self.djsSimilarArray.append(self.djObject)
self.similarArtistsCollection.reloadData();
}
})
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return djsSimilarArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: profileCellID, for: indexPath) as! DJProfileCell
cell.djprofile = djsSimilarArray[indexPath.item]
return cell
}
class DJProfileCell: UICollectionViewCell {
var djprofile: SimilarDJ? {
didSet {
guard let djImageProfile = djprofile?.image else {return}
guard let djNameProfile = djprofile?.name else {return}
let url = URL(string: djImageProfile)
djImageView.kf.indicatorType = .activity
djImageView.kf.setImage(with: url)
djImageLabel.text = djNameProfile
djImageLabel.adjustsFontSizeToFitWidth = true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup(){
self.backgroundColor = .white
self.addSubview(djImageView)
self.addSubview(djImageLabel)
}
let djImageView: UIImageView = {
let iv = UIImageView()
// iv.contentMode = .scaleAspectFit
// iv.backgroundColor = .green
return iv
}()
let djImageLabel: MarqueeLabel = {
let label = MarqueeLabel()
label.text = "Name"
label.textColor = UIColor.black
label.font = label.font.withSize(14)
label.textAlignment = .center
return label
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init has not been implemented")
}
}
struct SimilarDJ {
let image: String?
let name: String?
}
in cell class - djImageView and djImageLabel are never added to the view's hierarchy. I see no IBOutlet and no addSubview().

TableView inside horizontal scrolling collection view cell

Hello I have a tableview inside horizontal scrolling collection view as shown below.
http://recordit.co/pUyTbuOPsn
TableView cells get populated properly by tvdatasource but
since TableView is embedded in a CollectionViewCell methods such as didselectitematindexpath does not get called.
how can I properly setup tableviewdelegate methods with controller and collection view cell so that delegate methods can funnel through to the top controller?
its easy to populate but CALLING the methods are what I need help with :D
here is the code below
also I will be reusing this pattern all over the app. many tableviews won't be static and data will be dynamically fed from the API.
class AddItemViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
{
#IBOutlet weak var mainCollectionView: UICollectionView!
var currentCellPosition = 0
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.tintColor = UIColor.leafBlack()
automaticallyAdjustsScrollViewInsets = false
mainCollectionView.dataSource = self
mainCollectionView.delegate = self
mainCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
mainCollectionView.register(AddItemDetailsCollectionViewCell.self, forCellWithReuseIdentifier: "DetailsCell")
mainCollectionView.register(AddItemPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCell")
mainCollectionView.register(AddItemShippingCollectionViewCell.self, forCellWithReuseIdentifier: "ShippingCell")
if let flowLayout = mainCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.itemSize = mainCollectionView.frame.size
flowLayout.minimumInteritemSpacing = 0
flowLayout.sectionInset = UIEdgeInsets.zero
flowLayout.footerReferenceSize = CGSize.zero
flowLayout.headerReferenceSize = CGSize.zero
}
mainCollectionView.isPagingEnabled = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
if(indexPath.row == 0) {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DetailsCell", for: indexPath) as! AddItemDetailsCollectionViewCell
}else if(indexPath.row == 1) {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! AddItemPhotoCollectionViewCell
}else if(indexPath.row == 2) {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShippingCell", for: indexPath) as! AddItemShippingCollectionViewCell
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("yo")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: view.frame.width, height: view.frame.height)
}
#IBAction func showPrevCell(_ sender: Any) {
if (currentCellPosition > 0) {
currentCellPosition -= 1
mainCollectionView.scrollToItem(at: IndexPath.init(row: currentCellPosition, section: 0), at: .centeredHorizontally, animated: true)
}
}
#IBAction func showNextCell(_ sender: Any) {
if (currentCellPosition < 2) {
currentCellPosition += 1
mainCollectionView.scrollToItem(at:IndexPath.init(row: currentCellPosition, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
import Foundation
import UIKit
class AddItemDetailsCollectionViewCell: BaseAddItemCollectionViewCell {
#IBOutlet weak var cellTitleLabel: UILabel!
#IBOutlet weak var mainTableView: UITableView!
var detailFieldNames = ["Model Name", "Brand", "Size", "Description", "Condition"]
var containingVC: AddItemViewController?
override var nibName: String! {
get {
return "AddItemDetailsCollectionViewCell"
} set {}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
configView()
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
configView()
}
override func configView() {
mainTableView.dataSource = self
mainTableView.delegate = self
mainTableView.separatorStyle = .none
mainTableView.allowsSelection = false
let attributes = [NSFontAttributeName: UIFont(name: "Rokkitt-Thin", size: 22)!, NSForegroundColorAttributeName: UIColor.leafBlack(), NSKernAttributeName : 3.0] as [String : Any]
cellTitleLabel.attributedText = NSAttributedString(string: "Detail Info", attributes: attributes)
mainTableView.register(AddDetailTableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
}
}
extension AddItemDetailsCollectionViewCell: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! AddDetailTableViewCell
cell.checkBox.setCheckState(.mixed, animated: true)
//
}
}
extension AddItemDetailsCollectionViewCell: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? AddDetailTableViewCell {
cell.setupTitleLabel(detailFieldNames[indexPath.row])
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
class BaseAddItemCollectionViewCell: UICollectionViewCell {
var cell: UICollectionViewCell!
var nibName: String!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
configView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
configView()
}
func xibSetup() {
do {
try cell = loadCellFromNib()
// use bounds not frame or it'll be offset
cell.frame = bounds
// Make the view stretch with containing view
cell.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(cell)
} catch {
print("Failed to create view from nib")
}
}
func loadCellFromNib() throws -> UICollectionViewCell {
let bundle = Bundle.main
let nib = UINib(nibName: nibName, bundle: bundle)
let cell = (nib.instantiate(withOwner: self, options: nil)[0] as? UICollectionViewCell)!
return cell
}
func configView() {
}
}

Protocol UITableViewDataSource is not called from xib - Swift

I don't know why my protocol UITableViewDataSource is not execute when i run the APP.
Here my xib design:
My init of class from xib is: CustomSearchDestination
#IBOutlet weak var searchText: UITextField!
#IBOutlet weak var tableView: UITableView!
let xibName = "CustomSearchDestination"
var destinationListLocal: [Destinos] = []
var SearchViewControllerView: SearchViewController?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
xibSetup(xibName)
SearchViewControllerView = SearchViewController()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
searchText.delegate = self
tableView.delegate = self
tableView.dataSource = self
}
override init(frame: CGRect) {
super.init(frame : frame)
xibSetup(xibName)
}
Inside of this class have implemented the protocol UITableViewDelegate and UITableViewDataSource
extension CustomSearchDestination: UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("El count es: \(destinationListLocal.count)")
return destinationListLocal.count
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
searchText.text = selectedCell.textLabel!.text
}}
extension CustomSearchDestination: UITableViewDataSource {
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let index = indexPath.row as Int
if destinationListLocal.count == 0 {
if let str = destinationListLocal[index].desDestino {
cell.textLabel?.text = str
}
}
return cell
}}
Can someone point me my mistake?
EDIT: My hierarchy is:
I have a xib where i put other xib like this:
this is my class CustomViewHandler. So.. my class CustomSearchDestination is a class of the superClass CustomViewHandler.
At the same time is a class of CustomSearch
class CustomViewHandler : UIView {
var view: UIView!
var controllerView : UIView!
// Keyboard
var activeField : UITextField?
var isKeyboardVisible = false
var fixValue : CGFloat?
var keyboardSize : CGFloat = 280
fileprivate func loadViewFromNib(_ nibName: String) -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
// Assumes UIView is top level and only object in CustomView.xib file
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func xibSetup(_ nibName: String) {
view = loadViewFromNib(nibName)
// use bounds not frame or it'll be offset
view.frame = bounds
// Makes the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}}

Duplicate Objects in PFQueryCollectionViewController

I am fairly new to Swift and Parse and am attempting to use PFQueryCollectionViewController to load a set of images and titles. The problem is that my PFQueryCollectionViewCell is duplicating the same image and text label in the simulator although I have multiple objects within the class name I am querying. I have searched multiple discussion threads, but can't seem to find a solution that solves it. It's probably something super simple that I am overlooking but my eyes are starting to bleed!
Thanks in advance for your help.
FeedViewController (PFQueryCollectionViewController)
import Foundation
import UIKit
import Parse
import ParseUI
import Bolts
let reuseIdentifier:String = "feedCell"
class FeedViewController: PFQueryCollectionViewController, UICollectionViewDelegateFlowLayout {
let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure the PFQueryCollectionView
self.parseClassName = "Products"
self.pullToRefreshEnabled = true
self.paginationEnabled = true
self.objectsPerPage = 50
}
override func queryForCollection() -> PFQuery {
var query = PFQuery(className: "Products")
query.orderByAscending("createdAt")
return query
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> PFCollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as? FeedViewCell
let item = indexPath.item
for object in objects {
cell?.parseObject = object[item] as? PFObject
if let parseObject = object["url"] as? String? {
cell?.productImage?.image = nil
if var urlString: String? = parseObject as String? {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.productImage?.image = UIImage(data: imageData) } )}
} }
cell?.title?.text = object["title"] as? String
var text = object["title"] as? String
}
return cell!
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath ) {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
override func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 170, height: 300)
}
override func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
}
FeedViewCell (PFQueryCollectionViewCell)
import Foundation
import UIKit
import Parse
import ParseUI
class FeedViewCell: PFCollectionViewCell {
#IBOutlet weak var productImage: PFImageView?
#IBOutlet weak var title: UILabel?
var parseObject:PFObject?
}