ViewController loads only if the initial storyboard (swift) - ios

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()
}
}

Related

tableView reloadData doesn't work, delegate methods

I am trying to create new category in 1 view controller (AddCategoryViewController) and show it in table view controller (CategoryViewController). But there's an issue with reloading data.
New category item shows only after turning on and off the app, even when there is tableView.reloadData().
I tried to change the title of navigation in addButtonPressed function and the title changes immediately.
When I was using UIAlertView to add data, tableView.reloadData() worked. So I guess it's something with 2 view controllers and delegate methods?
Thanks for your help <3
show item:
import UIKit
import CoreData
class CategoryViewController: UITableViewController {
#IBOutlet weak var navigation: UINavigationItem!
var categoryArray = [Category]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
loadCategory()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "CategoryItemCell")
cell.textLabel?.text = categoryArray[indexPath.row].name
if let randomColor = categoryArray[indexPath.row].color {
cell.textLabel?.textColor = UIColor(hex: randomColor)
}
return cell
}
// MARK: - Table view data source
#IBAction func addPressed(_ sender: UIBarButtonItem) {
let addCategoryVC = storyboard?.instantiateViewController(withIdentifier: "AddCategoryViewController") as! AddCategoryViewController
addCategoryVC.delegate = self
present(addCategoryVC, animated: true, completion: nil)
}
// MARK: - CoreData methods
func saveCategory() {
do {
try context.save()
} catch {
print("Save error: \(error)")
}
tableView.reloadData()
}
func loadCategory(with request: NSFetchRequest<Category> = Category.fetchRequest()) {
do {
categoryArray = try context.fetch(request)
} catch {
print("Load error: \(error)")
}
tableView.reloadData()
}
func addCategory(name: String, description: String) {
let newCategory = Category(context: context.self)
newCategory.name = name
newCategory.descriptionOfCategory = description
newCategory.color = UIColor.random().toHex
saveCategory()
print("name form func: \(name)")
print("description from func: \(description)")
}
}
// MARK: AddCateogry delegate methods
extension CategoryViewController: AddCategoryDelegate {
func addButtonPressed(name: String, description: String) {
addCategory(name: name, description: description)
navigation.title = "I have changed!"
}
}
Add item:
import UIKit
protocol AddCategoryDelegate {
func addButtonPressed(name: String, description: String)
}
class AddCategoryViewController: UIViewController {
var delegate : AddCategoryDelegate!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var descriptionTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addCategoryButtonPressed(_ sender: UIButton) {
delegate.addButtonPressed(name: nameTextField.text!, description: descriptionTextField.text!)
dismiss(animated: true, completion: nil)
}
}
You only save the category to coredata inside addCategory , but you have to add the item to the array also , or call loadCategory before tableView.reloadData() inside saveCategory

UiTabController app setup

I am on the beginning stages of my project. It is a UITabbedApplication with three tabs. The tab at [0] position is the "Location picker", the [1] tab is the "view profiles" from the location picked in the Location picker view. Depending on the location that is first chosen I want the view profiles tab to show profiles from that specific location. Would I be able to do this with container views or is the way I want this set up not going to work? Any advice would be helpful.
//tab [0] choose location
class ChooseLocationVC: UIViewController {
#IBAction func chooseAction(_ sender: Any) {
if pageControl.currentPage == 0{
print("LA")
}
else if pageControl.currentPage == 1{
print("SF")
}else if pageControl.currentPage == 2{
print("NY")
}else if pageControl.currentPage == 3{
print("Miami")
}else if pageControl.currentPage == 4{
print("LasVegas")
}else if pageControl.currentPage == 5{
print("Chicago")
}
}
#IBOutlet weak var collectionView: UICollectionView!
var thisWidth:CGFloat = 0
#IBOutlet weak var pageControl: UIPageControl!
var imageArray = [UIImage(named: "LA"),UIImage(named: "SF"), UIImage(named: "NY"), UIImage(named: "Miami"), UIImage(named: "LasVegas"), UIImage(named: "Chicago")]
override func viewDidLoad() {
super.viewDidLoad()
setLabels()
// thisWidth = CGFloat(self.frame.width)
collectionView.delegate = self
collectionView.dataSource = 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.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
cell.locationImage.image = imageArray[indexPath.row]
return cell
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
setLabels()
print(pageControl.currentPage)
}
}
My StoryBoard :
A tab Bar Controller - >
-> VC2 tab[0]
-> VC3 tab[1]
My Struct Class that Will take data from VC2 To VC3
struct Global
{
static var Location : String!
}
My VC2 Class :
import UIKit
class VC2: UIViewController {
#IBOutlet weak var textTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool)
{
print("Called of vC2")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func saveValue(_ sender: Any)
{
Global.Location = self.textTF.text
}
}
My VC3 Class:
import UIKit
class VC3: UIViewController {
#IBOutlet weak var resultTf: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
print("Called of vC3")
if Global.Location != ""
{
self.resultTf.text = Global.Location
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Swift tableview in popover doesn't show data

I am trying to setup a popover view containing a textfield and a tableview, but I couldn't make the tableview to show the data. It would be much appreciated if you could help me on this.
On the main ViewController, I put a label to trigger the segue of popover,
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
#IBAction func popover(sender: AnyObject) {
self.performSegueWithIdentifier("ShowDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetails" {
if let controller = segue.destinationViewController as? UIViewController {
controller.popoverPresentationController!.delegate = self
controller.preferredContentSize = CGSize(width: 320, height: 50)
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
A PopoverCell is setup for the prototype cell,
import UIKit
class PopoverCellTableViewCell: UITableViewCell {
#IBOutlet weak var AreaCellLabel: 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
}
}
A PopoverControllerView is set for the popover itself.
import UIKit
class PopoverViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
var areas = [Area]()
// #IBOutlet weak var NewArea: UITextField!
// #IBOutlet weak var SaveNewArea: UIButton!
#IBOutlet weak var subtableView: UITableView!
override func viewDidLoad() {
subtableView.dataSource = self
subtableView.delegate = self
super.viewDidLoad()
LoadsampleArea()
// Do any additional setup after loading the view.
}
func LoadsampleArea () {
let area1 = Area(AreaName:"Moountain")!
let area2 = Area(AreaName:"ByHill")!
let area3 = Area(AreaName:"Yard")!
areas += [area1, area2, area3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return areas.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "AreaCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PopoverCellTableViewCell
let area = areas[indexPath.row]
cell.AreaCellLabel.text = area.AreaName
dismissViewControllerAnimated(true, completion:nil)
return cell
}
}
and a simple data file to put the data.
import UIKit
class Area {
var AreaName: String
init? (AreaName: String) {
self.AreaName = AreaName
if AreaName.isEmpty {
return nil
}
}
}
Where is your UITableView object in your PopoverViewController class ? I can't see any reference to it.
Maybe your didn't copy-paste it since the textfield is commented too, in this case I'll suggest to check if the delegate an datasource are set property.

Delegate returning nil - Swift

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!!

How change/create a new source type for UIImagePicker (SWIFT)

I am new in iOS development and I need help.
I use UIImagePicker so that the user selects his image.
I want that user selects pictures located in a folder of the application and not the iOS library. All this using UIImagePicker. Is this possible?
If I am wrong please redirect me to a website or tutorial.
Thank you all.
Sample code :
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet var PhotoOpeningView: UIImageView!
let userDefaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
#IBAction func ChooseAImageBTN(sender: AnyObject) {
let imagePickerView = UIImagePickerController()
imagePickerView.delegate = self
imagePickerView.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
self.presentViewController(imagePickerView, animated: true, completion: nil)
}
#IBAction func btnSave(sender: UIButton) {
let LoadSaveNo = PhotoOpeningView
userDefaults.setObject(LoadSaveNo, forKey: "LoadSave")
userDefaults.synchronize()
}
func imagePickerController(picker :UIImagePickerController,
didFinishPickingMediaWithInfo info : [NSObject : AnyObject]) {
var Image = info[UIImagePickerControllerOriginalImage] as UIImage
PhotoOpeningView.image = Image
self.dismissViewControllerAnimated(true, completion: nil)
}
//This class has UIButton when you click on button it opens PhotoPickersVC. Which will show all images from your application
class ViewController: UIViewController,PhotoPickersDelegate {
#IBOutlet var imageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func buttonBrowsePhotos(sender: UIButton)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc :UINavigationController = storyboard.instantiateViewControllerWithIdentifier("PhotoNC") as UINavigationController
var array:NSArray = nc.viewControllers as NSArray
let vc:PhotoPickersVC=array.objectAtIndex(0) as PhotoPickersVC;
vc.delegate=self;
self.presentViewController(nc, animated: true, completion: nil)
}
func selectPhoto(image: UIImage)
{
imageView.image=image;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//Protocol used to send photo to ViewController class using delegate
protocol PhotoPickersDelegate
{
func selectPhoto(var image : UIImage)
}
//This class shows all the photos of your application
class PhotoPickersVC: UICollectionViewController {
let reuseIdentifier = "Cell"
var myImages :NSArray?
var delegate : PhotoPickersDelegate?
override func viewDidLoad() {
super.viewDidLoad()
var myBundle : NSBundle = NSBundle.mainBundle();
myImages = myBundle.pathsForResourcesOfType("jpeg", inDirectory: nil);
}
#IBAction func buttonCancel(sender: UIButton)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return myImages!.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as PhotoCellCollectionViewCell
print(cell);
var imageName=myImages?.objectAtIndex(indexPath.row).lastPathComponent
var imageName1 :NSString=imageName!
var image:UIImage=UIImage(named: imageName1)!
cell.imageView.image=image
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
if((self.delegate) != nil)
{
var imageName=myImages?.objectAtIndex(indexPath.row).lastPathComponent
var imageName1 :NSString=imageName!
var image:UIImage=UIImage(named: imageName1)!
delegate?.selectPhoto(image)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
//This class used to subclass UICollectionViewCell which is used in PhotoPickersVC
class PhotoCellCollectionViewCell: UICollectionViewCell {
#IBOutlet var imageView: UIImageView!
}
Having a look through the UIImagePickerController documentation, I don't think what you're asking is possible. If you have a look at UIImagePickerControllerSourceType, you'll see there are only 3 possibilities, PhotoLibrary, SavedPhotosAlbum, or Camera, which doesn't leave a whole lot of room for trying out a source type of 'custom'.
My recommendation is to use a UICollectionView to display your images and allow your user to choose from them using collection view delegate methods. You could whip one up quite quickly if all you need is a simple image picker.
Objective-C:
http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12
Swift:
http://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-1

Resources