Delegate returning nil - Swift - ios

This code is simple:
import UIKit
import CoreData
class PhotoList: UIViewController, UITableViewDelegate, UITableViewDataSource, sendDetailsDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBOutlet var tableView: UITableView!
var whoTookArray: [String] = []
var imageArray: [UIImage] = []
func sendDetails (name: String, photo: UIImage) {
whoTookArray.append(name)
imageArray.append(photo)
tableView!.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return whoTookArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
let row = indexPath.row
let whoTookName = whoTookArray[row]
let image = imageArray[row]
cell.textLabel?.text = whoTookName
cell.imageView!.image = image
return cell
}
}
and
import UIKit
import CoreData
protocol sendDetailsDelegate {
func sendDetails(name: String, photo: UIImage)
}
class Details: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
tapGestureRecognizer.numberOfTapsRequired = 1
imageSelected.addGestureRecognizer(tapGestureRecognizer)
imageSelected.userInteractionEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet var whoTookTextField: UITextField!
#IBOutlet var imageSelected: UIImageView!
var delegate: sendDetailsDelegate?
//Pick the image by tapping, accessing the PhotoLibrary
func chooseImage(recognizer: UITapGestureRecognizer) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
//Put the selected image into the screen
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(288,148))
var sizeOfImageView: CGRect = imageSelected.frame
sizeOfImageView.size = smallPicture.size
imageSelected.frame = sizeOfImageView
imageSelected.image = smallPicture
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
func scaleImageWith(image: UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
#IBAction func addButton(sender: AnyObject) {
if whoTookTextField == nil || imageSelected == nil { return }
if imageSelected == nil { return }
let whoTook = whoTookTextField.text
let image = imageSelected.image
println("\(delegate)")
delegate!.sendDetails(whoTook, photo: image!)
println("whoTook: \(whoTook) image: \(image)")
if let navigation = self.navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
I'm delegating a text and an image to the PhotoList view controller, but it crashes in the delegate line here:
delegate!.sendDetails(whoTook, photo: image!)
The print line says it's nil. Does anyone know why? Thanks!
EDIT
Solved!

add this code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "toPhotoList") {
let view = segue.destinationViewController as! Details
view.delegate = self
}
}
And all your trouble is gone! Tableview updated successfully!
Thanks for the help!!

Related

How can I upload images from gallery to TableViewCell

PostViewController
I'm working on a social app. In which I want to upload photos from gallery to my TableViewCell by UploadButton. By programmatically I created some posts, as shown in MainScreenViewController, like facebook or instagram. But now I want to add a photo by picking up from gallery and upload to the VC.
This is my PostViewController in which I'm getting a photo from library and now I want to post it on MainScreenViewController's ViewControllersTableView.
Kindly help at this point
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
class PostViewController: UIViewController {
var ref = DatabaseReference.init()
#IBOutlet weak var txtText: UITextField!
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var btnUpload: UIButton!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
btnUpload.designButton(borderWidth: 0, borderColor: UIColor.clear)
self.ref = Database.database().reference()
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: #selector(PostViewController.openGallery(tapGesture:)))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer(tapGesture)
}
func saveFIRData() {
self.uploadImage(self.myImageView.image!) { url in
self.saveImage(name: self.txtText.text!, profileURL: url!) { success in
if success != nil {
print("Good")
}
}
}
}
#objc func openGallery(tapGesture: UITapGestureRecognizer) {
self.setUpImagePicker()
}
#IBAction func btnSaveClick(_ sender: UIButton) {
self.saveFIRData()
}
}
extension PostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func setUpImagePicker() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.delegate = self
imagePicker.isEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
myImageView.image = image
self.dismiss(animated: true, completion: nil)
}
}
extension PostViewController {
func uploadImage(_ image:UIImage, completion: #escaping ((_ url: URL?) -> ())) {
let storageRef = Storage.storage().reference().child("myImage.png")
let imgData = myImageView.image?.pngData()
let metaData = StorageMetadata()
metaData.contentType = "image/png"
storageRef.putData(imgData!, metadata: metaData) { (metdata, error) in
if error == nil {
print("Success")
storageRef.downloadURL(completion: { (url, error) in
completion(url!)
})
} else {
print("error in save image")
completion(nil)
}
}
}
func saveImage(name: String, profileURL: URL, completion: #escaping ((_ url: URL?) -> ())) {
let dict = ["name": "Omer", "text": txtText.text!, "profileURL": profileURL.absoluteString] as [String: Any]
self.ref.child("chat").childByAutoId().setValue(dict)
}
}
MainScreenViewController
import UIKit
import Firebase
import FirebaseAuth
class MainScreenViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var cardTableView: UITableView!
let pictures: [UIImage] = [UIImage(named: "1")!, UIImage(named: "2")!, UIImage(named: "3")!]
let images: [UIImage] = [UIImage(named: "aa")!, UIImage(named: "ab")!, UIImage(named: "ac")!]
let titles: [String] = ["Che Guevara", "BatMan", "Information Technology"]
let descriptions: [String] = ["Ernesto Che Guevara was an Argentine Marxist revolutionary, guerrilla leader.", "Batman ventures into Gotham City's underworld.", "Information technology is defined as a broad term that includes the development."]
override func viewDidLoad() {
super.viewDidLoad()
cardTableView.delegate = self
cardTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 400
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cardCell", for: indexPath) as! CardCell
cell.configure(picture: pictures[indexPath.row], img: images[indexPath.row], title: titles[indexPath.row], description: descriptions[indexPath.row])
return cell
}
}
CardCell
import UIKit
import Firebase
import FirebaseAuth
class CardCell: UITableViewCell {
#IBOutlet weak var cardView: UIView!
#IBOutlet weak var pictureView: UIImageView!
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var btnLike: UIButton!
// set up the cell
func configure(picture: UIImage, img: UIImage, title: String, description: String) {
pictureView.image = picture
profileImage.image = img
titleLabel.text = title
descriptionLabel.text = description
cardView.layer.shadowColor = UIColor.gray.cgColor
cardView.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
cardView.layer.shadowOpacity = 1.0
cardView.layer.masksToBounds = false
cardView.layer.cornerRadius = 2.0
}
#IBAction func btnLike_Click(_ sender: UIButton) {
if btnLike.tag == 0 {
btnLike.setImage(UIImage(named: "h1"), for: .normal)
btnLike.tag = 1
} else {
btnLike.setImage(UIImage(named: "h4"), for: .normal)
btnLike.tag = 0
}
}
}
I think you can use closure to pass data back to MainVC which I found it lot easier
Create a closure in PostViewController :
var uploadedImage : ((UIImage)->Void)?
Assign the uploadedImage property before the picker is dismissed
uploadedImage(myUplodedImage)?
Use the property of the closure when you initiate it on MainViewController
let vc = PostViewController(nibName : "something", bundle : nil)
vc.uploadedImage = {
// Add some action here when the PostViewController dismiss
}
navigationController.pushViewController(vc, animated : true)
Additional references :
Passing Data Between View Controllers

Why isn't my Image displaying in the UIImageView?

I want to get an if statement which, if the selected button corresponded to the first image view, set it to the first image, else set it to the second image view... But, once I select the image from the image picker, it just ignores it and moves on like if nothing happened.
Here is my code:
(it down under the image picker controller func...)
class UploadSubPostCell: UICollectionViewCell {
#IBOutlet weak var previewStep: UIImageView!
}
class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var previewImage: UIImageView!
#IBOutlet weak var postBtn: UIButton!
#IBOutlet weak var selectBtn: UIButton!
#IBOutlet weak var postscollectionview: UICollectionView!
#IBOutlet weak var selectStepsBtn: UIButton!
var picker = UIImagePickerController()
var isThumbnailImage = true
var subpostsArray = [UIImage]()
var subposts = [SubPost]()
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBarItems()
picker.delegate = self
}
func setupNavigationBarItems() {
navigationItem.title = "Upload"
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
let path = IndexPath(item: 0, section: 0)
let cell = self.postscollectionview.cellForItem(at: path) as? UploadSubPostCell
if isThumbnailImage{
previewImage.image = image
} else {
cell?.previewStep.image = image
}
selectBtn.isHidden = false
selectStepsBtn.isHidden = false
postBtn.isHidden = false
if isThumbnailImage == false {
subpostsArray.append(image)
subposts.count + 1
print("Appended image to array:", subpostsArray)
}
}
picker.dismiss(animated: true, completion: nil)
}
#IBAction func selectStepPressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
isThumbnailImage = false
self.present(picker, animated: true, completion: nil)
}
#IBAction func selectPressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
isThumbnailImage = true
self.present(picker, animated: true, completion: nil)
}
#IBAction func addNewPressed(_ sender: Any) {
}
#IBAction func postPressed(_ sender: Any) {
AppDelegate.instance().showActivityIndicator()
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://mobile-d9fcd.appspot.com")
let key = ref.child("posts").childByAutoId().key
let imageRef = storage.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.previewImage.image!, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata, error) in
if error != nil {
print(error!.localizedDescription)
AppDelegate.instance().dismissActivityIndicator()
return
}
imageRef.downloadURL(completion: { (url, error) in
if let url = url {
let feed = ["userID" : uid,
"pathToImage" : url.absoluteString,
"likes" : 0,
"author" : Auth.auth().currentUser!.displayName!,
"postID" : key] as [String : Any]
let postFeed = ["\(key)" : feed]
ref.child("posts").updateChildValues(postFeed)
AppDelegate.instance().dismissActivityIndicator()
self.picker.dismiss(animated: true, completion: nil)
}
})
}
uploadTask.resume()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.postImage.downloadImage(from: self.posts[indexPath.row].pathToImage)
cell.authorLabel.text = self.posts[indexPath.row].author
cell.likeLabel.text = "\(self.posts[indexPath.row].likes!) Likes"
cell.postID = self.posts[indexPath.row].postID
}
}
}
In didFinishPickingMediaWithInfo, you should save the image with the dataSource, if you know what cell the image goes into, use tableView.reloadRows(at indexPaths:) to reload the cell. Add the image to cell.previewStep.image in cellForRowAt()
if you are using swift version 4.2 and above, you should be replacing:
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
by:
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {

Why is my code not working? - setObjectForKey: key cannot be nil

Working on an app where I store data on Firebase and load the data into my TableView. Had to change the (old) code a little from a tutorial i found so I hope someone can spot the mistake i made. The user can add an event with a: name, date, description (all strings) and Image. This data is loaded into the TableView onto three "labels" and and image on top.
import UIKit
import Firebase
import FirebaseDatabaseUI
class EventViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//outlets for text & image
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var eventName: UITextField!
#IBOutlet weak var eventDate: UITextField!
#IBOutlet weak var eventDes: UITextView!
//Database connection
let rootref = FIRDatabase().reference()
var imagePicker: UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func submitEvent(sender: AnyObject) {
let name = eventName.text
let date = eventDate.text
let text = eventDes.text
var data: NSData = NSData()
if let image = photoImageView.image {
data = UIImageJPEGRepresentation(image,0.1)!
}
let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let user: NSDictionary = ["name":name!, "date":date!, "text":text!, "photoBase64":base64String]
//Add firebase child node
let event = FIRDatabase().reference().child(name!)
// Write data to Firebase
event.setValue(user)
navigationController?.popViewControllerAnimated(true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
//UIImagePickerControllerDelegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func addPicture(sender: AnyObject) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
} else {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion:nil)
}
}
}
My TABLEVIEWCONTROLLER
import UIKit
import Firebase
class EventTableViewController: UITableViewController {
#IBOutlet weak var eventImage: UIImageView!
#IBOutlet weak var eventName: UILabel!
#IBOutlet weak var eventDate: UILabel!
#IBOutlet weak var eventText: UITextView!
let rootref = FIRDatabase().reference()
var items = [NSDictionary]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
items = [NSDictionary]()
FIRDatabase.load()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//TableView Data
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
configureCell(cell, indexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let dict = items[indexPath.row]
let name = dict["name"] as! String
// delete data from firebase
let event = FIRDatabase().reference().child(name)
event.removeValue()
}
}
// MARK:- Configure Cell
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
let dict = items[indexPath.row]
eventName.text = dict["name"] as? String
eventDate.text = dict["name"] as? String
eventText.text = dict["name"] as? String
let base64String = dict["photoBase64"] as! String
populateImage(cell, imageString: base64String)
}
func populateImage(cell:UITableViewCell, imageString: String) {
let decodedData = NSData(base64EncodedString: imageString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
cell.imageView!.image = decodedImage
}
//load data from Firebase
func loadDataFromFirebase() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
rootref.observeEventType(.Value, withBlock: { snapshot in
var tempItems = [NSDictionary]()
for item in snapshot.children {
let child = item as! FIRDataSnapshot
let dict = child.value as! NSDictionary
tempItems.append(dict)
}
self.items = tempItems
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
}
IMAGE TO GET AN IDEA OF MY WORK
My app so far
Look at this line:
let user: NSDictionary = ["name":name!, "date":date!, "text":text!, "photoBase64":base64String]
You are doing a lot of forced unwrapping here. In fact, you do a lot of forced unwrapping in several places. When you do this you are saying "I am 100% sure there will ALWAYS be a value here". Avoid this a nearly all costs. That line should look like this.
if let unwrappedName = name , unwrappedDate = date, unwrappedText = text{
let user: NSDictionary = ["name":unwrappedName, "date":unwrappedDate, "text":unwrappedText, "photoBase64":base64String]
}
Unwrapping optionals like this will keep your app from crashing. You should put a breakpoint here to see what value is nil. Every time you use a ! you should think VERY carefully about about it.
I believe the error is where you set up your database connection.
You have: let rootref = FIRDatabase().reference()
It should be:let rootref = FIRDatabase().database().reference()
I was getting the same error and this fixed it for me.

How do I pass the same textview, button, and label after clicking the Cell swift?

I would like to make it so that when the user clicks on the cell, it shows exactly everything in the cell. TextView, Buttons, and label. How can I do this?
Here is the code:
TableCell:
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var textView: UITextView!
#IBAction func 1Button(sender: AnyObject) {
}
#IBAction func 2Button(sender: AnyObject) {
}
#IBOutlet weak var counter: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
TableViewController:
import UIKit
let reuseIdentifier = "Cell"
class UserFeedTableViewController: UITableViewController, ComposeViewControllerDelegate {
private var posts: [PFObject]? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
Downloader.sharedDownloader.queryForPosts()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "queryFeeds:", name: queryNotification, object: nil)
}
// Notification SEL
func queryFeeds(notification: NSNotification) {
posts = notification.object as? [PFObject]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "postSegue" {
let nav = segue.destinationViewController as! UINavigationController
let composeVc = nav.topViewController as! ComposeViewController
composeVc.delegate = self
}
if segue.identifier == "commentsSegue" {
let vc = segue.destinationViewController as! CommentsViewController
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPathForCell(cell)
let object = posts![indexPath!.row]
vc.postObject = object
}
}
//dismiss compose vc
func dismissComposeViewController(ViewController: ComposeViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func reloadTableViewAfterPosting() {
dismissViewControllerAnimated(true, completion: nil)
Downloader.sharedDownloader.queryForPosts()
}
}
extension ViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return posts?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UserFeedTableViewCell
// Configure the cell...
if let posts = posts {
let object = posts[indexPath.row]
cell.textView?.text = object["post"] as? String
}
return cell
}

ViewController loads only if the initial storyboard (swift)

I'm using MVCarouselCollectionView framework for an image gallery
View a photo gallery of only works if it is the storyboard of the initial
Project Link: link download code
If I put the gallery view to be the initial, it will work. however if I put her to be the second view and use the following / push will not work
Gallery code
import UIKit
import MVCarouselCollectionView
import QuartzCore
import Alamofire
class GaleriaDeFotosViewController: UIViewController, MVCarouselCollectionViewDelegate {
#IBOutlet var pageControl: UIPageControl!
#IBOutlet var collectionView : MVCarouselCollectionView!
var imagePaths : [String] = []
// Closure to load local images with UIImage.named
var imageLoader: ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) = {
(imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) in
imageView.image = UIImage(named:imagePath)
completion(newImage: imageView.image != nil)
}
#IBAction func BtnCarregar(sender: AnyObject) {
configureCollectionView()
carregaFotoModo1()
}
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
carregaFotoModo1()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureCollectionView() {
view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.pageControl.numberOfPages = imagePaths.count
collectionView.selectDelegate = self
collectionView.imagePaths = imagePaths
collectionView.commonImageLoader = self.imageLoader
collectionView.maximumZoom = 2.0
collectionView.pagingEnabled = true
collectionView.reloadData()
}
// MARK: MVCarouselCollectionViewDelegate
func carousel(carousel: MVCarouselCollectionView, didSelectCellAtIndexPath indexPath: NSIndexPath) {
// Do something with cell selection
}
func carousel(carousel: MVCarouselCollectionView, didScrollToCellAtIndex cellIndex : NSInteger) {
// Page changed, can use this to update page control
self.pageControl.currentPage = cellIndex
}
func addAsChildViewController(parentViewController : UIViewController, attachToView parentView: UIView)
{
parentViewController.addChildViewController(self)
self.didMoveToParentViewController(parentViewController)
parentView.addSubview(self.view)
self.autoLayout(parentView)
}
func autoLayout(parentView: UIView) {
self.matchLayoutAttribute(.Left, parentView:parentView)
self.matchLayoutAttribute(.Right, parentView:parentView)
self.matchLayoutAttribute(.Bottom, parentView:parentView)
self.matchLayoutAttribute(.Top, parentView:parentView)
}
func matchLayoutAttribute(attribute : NSLayoutAttribute, parentView: UIView) {
parentView.addConstraint(
NSLayoutConstraint(item:self.view, attribute:attribute, relatedBy:NSLayoutRelation.Equal, toItem:parentView, attribute:attribute, multiplier:1.0, constant:0))
}
// MARK: FullScreenViewControllerDelegate
func willCloseWithSelectedIndexPath(indexPath: NSIndexPath) {
self.collectionView.resetZoom()
self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.CenteredHorizontally, animated:false)
}
func carregaFotoModo1()
{
self.imageLoader = imageViewLoadFromPath
self.imagePaths = [
"http://li.zoocdn.com/bb3d7c42506f563c1174828c97522728a87cfae8_645_430.jpg",
"http://li.zoocdn.com/162fd32ce15911cba3dcdf27a8a37238708991bc_645_430.jpg",
"http://li.zoocdn.com/9e17e58963944f4a6695c56561f1bd4ee0803cba_645_430.jpg",
"http://li.zoocdn.com/ffdbb7c884427a1d599f052cae4f205bf63373cf_645_430.jpg",
]
println(self.imagePaths)
self.configureCollectionView()
}
}

Resources