Swift: Building a Menu in a CollectionView With CollectionViewCell Segue - swift

I am building a menu using CollectionView and programmatically trying to attach 5 buttons. I can not figure out how to connect the buttons to segues. The buttons activate a container view which then switches content within that view. This is what I have so far for the MenuContainerViewController which is embedded within a MainMenuViewController. Any help would be appreciated.
import UIKit
class MenuContainerViewController: UIViewController {
var firstVC: MainMenuViewController?
enum SegueIdentifier: String {
case SegueToTravelViewIdentifier = "SegueToTravelViewIdentifier"
case SegueToHistoryViewIdentifier = "SegueToHistoryViewIdentifier"
case SegueToLimitsViewIdentifier = "SegueToLimitsViewIdentifier"
case SegueToBalanceViewIdentifier = "SegueToBalanceViewIdentifier"
case SegueToEditViewIdentifier = "SegueToEditViewIdentifier"
case SegueToHelpViewIdentifier = "SegueToHelpViewIdentifier"
init?(optionalRawValue: String?) {
if let value = optionalRawValue {
switch value {
case "SegueToTravelViewIdentifier": self = .SegueToTravelViewIdentifier
case "SegueToHistoryViewIdentifier": self = .SegueToHistoryViewIdentifier
case "SegueToLimitsViewIdentifier": self = .SegueToLimitsViewIdentifier
case "SegueToBalanceViewIdentifier": self = .SegueToBalanceViewIdentifier
case "SegueToEditViewIdentifier": self = .SegueToEditViewIdentifier
case "SegueToHelpViewIdentifier": self = .SegueToHelpViewIdentifier
default: return nil
}
}
return nil
}
}
var vc : UIViewController!
var segueIdentifier : String!
var lastViewController: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
segueIdentifierReceivedFromParent("mainButton")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func segueIdentifierReceivedFromParent(button: String){
if button == "mainButton"
{
self.segueIdentifier = "main"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
else if button == "travelButton"
{
self.segueIdentifier = "travel"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
else if button == "balanceButton"
{
self.segueIdentifier = "balance"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
else if button == "limitsButton"
{
self.segueIdentifier = "limits"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
else if button == "historyButton"
{
self.segueIdentifier = "history"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
else if button == "helpButton"
{
self.segueIdentifier = "help"
self.performSegueWithIdentifier(self.segueIdentifier, sender: nil)
}
}
/*
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == segueIdentifier{
if lastViewController != nil{
lastViewController.view.removeFromSuperview()
}
vc = segue.destinationViewController
self.addChildViewController(vc)
vc.view.frame = CGRect(x: 0,y: 0, width: self.view.frame.width,height: self.view.frame.height)
self.view.addSubview(vc.view)
vc.didMoveToParentViewController(self)
lastViewController = vc
}
}
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let segueIdentifierValue = SegueIdentifier(rawValue: segue.identifier!) {
if lastViewController != nil {
lastViewController.view.removeFromSuperview()
}
vc = segue.destinationViewController
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
lastViewController = vc
switch segueIdentifierValue {
case .SegueToTravelViewIdentifier:
print("travel")
case .SegueToHistoryViewIdentifier:
print("history")
case .SegueToLimitsViewIdentifier:
print("limits")
case .SegueToBalanceViewIdentifier:
print("balance")
case .SegueToEditViewIdentifier:
print("edit")
case .SegueToHelpViewIdentifier:
print("help")
}
}
}
}
and this is the MainMenuViewController:
class MainMenuViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
//Container View
#IBOutlet weak var contain: UIView!
//Slide Menu Collection View
let reuseIdentifier = "cell"
var menus = Array<String>()
var containerView: MenuContainerViewController?
#IBOutlet weak var collectionView: UICollectionView!
#IBAction func menuButtonPressed(sender: AnyObject) {
self.performSegueWithIdentifier("travel", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//Button names
menus = ["button_instore", "button_atm", "button_online", "button_travel", "button_balance", "button_limits", "button_history", "button_edit", "button_help"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func travel(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("travelButton")
}
#IBAction func balance(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("balanceButton")
}
#IBAction func limits(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("limitsButton")
}
#IBAction func history(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("historyButton")
}
#IBAction func help(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("helpButton")
}
#IBAction func main(sender: AnyObject) {
containerView!.segueIdentifierReceivedFromParent("mainButton")
}
/*override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "container"{
containerView = segue.destinationViewController as? MenuContainerViewController
}
}
*/
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.navigationBar.translucent = true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.menus.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
/*
func MenuContainerViewController(sender : UIButton) {
let selectedButtonCell = sender.superview as! UICollectionViewCell
let indexPath = collectionView.indexPathForCell(selectedButtonCell)
if indexPath!.row == 0 {
}
}
*/
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
//cell.menuLabel.text = self.menus[indexPath.item]
cell.menuButton?.image = UIImage(named: menus[indexPath.row])
cell.menuButtonPressed.tag = indexPath.row
//cell.menuButtonPressed.addTarget(self, action: #selector(MenuContainerViewController), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.item)!")
}
}

Related

Blank labels after data passing in Swift 4?

I am currently trying to pass data from my table view controller to a second view controller but my labels and image are appearing as blank in the second view controller.
This is my main event view controller:
class EventsTableViewController: PFQueryTableViewController {
override func queryForTable() -> PFQuery<PFObject> {
let query = PFQuery(className: "Events")
//query.order(byAscending: "location")
query.order(byAscending: "date")
return query
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Upcoming Events"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MasterToDetail" {
let detailVC = segue.destination as! DetailViewController
detailVC.myEventCell = sender as? EventCell
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! EventCell
cell.dateLabel.text = object?.object(forKey: "date") as? String
cell.locationLabel.text = object?.object(forKey: "location") as? String
cell.nameLabel.text = object?.object(forKey: "name") as? String
let imageFile = object?.object(forKey: "image") as? PFFile
cell.eventImage.image = UIImage(named: "download")
cell.eventImage.file = imageFile
cell.eventImage.loadInBackground()
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "MasterToDetail", sender: EventCell())
}
#IBAction func reloadTable(_ sender: Any) {
self.loadObjects()
}
#IBAction func onSignOutTapped(_ sender: Any) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
performSegue(withIdentifier: "signOutSegue", sender: nil)
} catch {
print (error)
}
}
}
and my second view controller:
class DetailViewController: UIViewController {
#IBOutlet weak var detailImageView: UIImageView!
#IBOutlet weak var detailNameLabel: UILabel!
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var detailLocationLabel: UILabel!
var myEventCell: EventCell?
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
func setUI () {
detailNameLabel.text = myEventCell?.nameLabel.text
detailImageView.image = myEventCell?.eventImage.image
detailLocationLabel.text = myEventCell?.locationLabel.text
}
}
As you send an empty cell here
performSegue(withIdentifier: "MasterToDetail", sender: EventCell())
You need
let cell = tableView.cellForRow(at:indexPath)
performSegue(withIdentifier: "MasterToDetail", sender:cell)

update UIViewController in Real Time from Popover Viewcontroller in Swift 4

right now i'm experimenting with SceneKit DebugOptions.
i'm trying to update/ show Scenekits Debug Options in real time, using switch controllers from a Popover ViewController.
i've tried many things, like UserDefaults, Delegation and Protocols, but stil i wasn't able to see the result in real time, every time i have to kill the app en relaunch it to see the results.
so, i would be greatfull if someone would have an answer to my question :D
extension i added to my MainVC
extension ViewController: UIPopoverPresentationControllerDelegate, DebugOptions {
func wireFrameEnabled(enabled: Bool) {
if enabled == true {
print(enabled)
}
}
func showCameraEnabled(enabled: Bool) {
}
func showAllDebugOptions(enabled: Bool) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let popoverController = segue.destination.popoverPresentationController, let button = sender as? UIButton else { return }
popoverController.delegate = self
popoverController.sourceRect = button.bounds
let debugMenuVC = popoverController.presentedViewController as! DebugMenuVC
debugMenuVC.delegate? = self
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
Protocol
protocol DebugOptions {
func wireFrameEnabled(enabled: Bool)
func showCameraEnabled(enabled: Bool)
func showAllDebugOptions(enabled: Bool)
}
DebugMenuVC
class DebugMenuVC: UIViewController {
#IBOutlet weak var bgView: UIView!
#IBOutlet weak var showWireFrameSwitch: UISwitch!
#IBOutlet weak var showCameraSwitch: UISwitch!
#IBOutlet weak var showAllSwitch: UISwitch!
var delegate: DebugOptions?
override func viewWillLayoutSubviews() {
preferredContentSize = CGSize(width: 150, height: 300)
}
override func viewDidLoad() {
super.viewDidLoad()
buttonCheck()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
#IBAction func aSwitchBtnWasPressed( _ sender: UISwitch ) {
if (sender.tag == 0) && (sender.isOn == true) {
userDefaults.set(true, forKey: SHOW_WIRE_FRAME)
delegate?.wireFrameEnabled(enabled: true)
} else if (sender.tag == 0) && (sender.isOn == false) {
userDefaults.set(false, forKey: SHOW_WIRE_FRAME)
delegate?.wireFrameEnabled(enabled: false)
}
}
func buttonCheck() {
if userDefaults.bool(forKey: SHOW_WIRE_FRAME) == true{
showWireFrameSwitch.isOn = true
} else {
showWireFrameSwitch.isOn = false
}
}
}
in debubMenuVC.delegate shouldn't be an optional. thats the reason the delegation method always failed :D
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let popoverController = segue.destination.popoverPresentationController, let button = sender as? UIButton else { return }
popoverController.delegate = self
popoverController.sourceRect = button.bounds
let debugMenuVC = popoverController.presentedViewController as! DebugMenuVC
debugMenuVC.delegate? = self
}

CoreData not Persisting?

I am saving an exercise into core data and calling it into the table, this works in terms of carrying the info from the user input into the table, however the coredata doesnt persist so when i re open the app, the entry is lost.
It was actually working yesterday and seems to have broken, but I havent made a change that would effect this as far as im aware. The one thing i found when debugging is that when I loaded the app its meant to point at the sql database in my console, however its changed to a .configurationprofiles file? Could this be a cause and what would the fix be? I will include the code for the tableview and the code for the user entry form below to show the information flow. Let me know if any other data is needed to be added.
import Foundation
import UIKit
import CoreData
class ExerciseEditorController: UIViewController, UITextFieldDelegate {
var managedObjectContext: NSManagedObjectContext?
var userRepsCount = Int()
var userSetsCount = Int()
#IBOutlet weak var userExerciseName: UITextField!
#IBOutlet weak var userExerciseSetCounter: UILabel!
#IBOutlet weak var userExerciseRepsCounter: UILabel!
#IBOutlet weak var userExerciseWeight: UITextField!
#IBAction func userSetsStepper(_ sender: UIStepper) {
userExerciseSetCounter.text = Int(sender.value).description
self.userSetsCount = Int(sender.value)
}
#IBAction func userRepsStepper(_ sender: UIStepper) {
userExerciseRepsCounter.text = Int(sender.value).description
self.userRepsCount = Int(sender.value)
}
#IBAction func cancelExerciseEditor(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
#IBAction func saveExerciseToWorkout(_ sender: Any) {
createExercise()
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = (UIColor.customBackgroundGraphite())
userExerciseSetCounter.text = String(userSetsCount)
userExerciseRepsCounter.text = String(userSetsCount)
userExerciseWeight.delegate = self
userExerciseWeight.keyboardType = .numbersAndPunctuation
}
func createExercise() {
let userExerciseWeightSet = Double(self.userExerciseWeight.text!) //make this safe!
guard let managedObjectContext = managedObjectContext else { return }
let userExercise = UserExercise(context: managedObjectContext)
userExercise.name = userExerciseName.text
userExercise.sets = Int64(userSetsCount)
userExercise.reps = Int64(userRepsCount)
userExercise.weight = userExerciseWeightSet! //make this safe!
userExercise.createdAt = Date().timeIntervalSince1970
}
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance:CGFloat = -130
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
}
else {
movement = -movementDistance
}
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:false)
}
}
And this is the tableview:
import Foundation
import UIKit
import CoreData
class WorkoutDesignerController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
#IBAction func unwindToWorkoutDesigner(segue: UIStoryboardSegue) {}
#IBOutlet weak var workoutDesignerTable: UITableView!
#IBOutlet weak var tapToAddExercise: UILabel!
#IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
#IBAction func cancelWorkoutDesigner(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToTemplatesWithSegue", sender: self)
}
private let persistentContainer = NSPersistentContainer(name: "Lift")
override func viewDidLoad() {
super.viewDidLoad()
setupView()
workoutDesignerTable.delegate = self
workoutDesignerTable.dataSource = self
view.backgroundColor = (UIColor.customBackgroundGraphite())
persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
if let error = error {
print("Unable to Load Persistent Store")
print("\(error), \(error.localizedDescription)")
} else {
self.setupView()
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError), \(fetchError.localizedDescription)")
}
self.updateView()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let userExercises = fetchedResultsController.fetchedObjects else { return 0 }
return userExercises.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? RoutineTableViewCell else {
fatalError("Unexpected Index Path")
}
cell.backgroundColor = UIColor.customBackgroundGraphite()
cell.textLabel?.textColor = UIColor.white
let userExercise = fetchedResultsController.object(at: indexPath)
cell.nameLabel.text = userExercise.name
cell.repsLabel.text = String(userExercise.reps)
cell.setsLabel.text = String(userExercise.sets)
cell.weightLabel.text = String(userExercise.weight)
return cell
}
private func setupView() {
setupMessageLabel()
updateView()
}
private func setupMessageLabel() {
tapToAddExercise.text = "Tap + To Add An Exercise To The Routine"
}
fileprivate func updateView() {
var hasUserExercises = false
if let UserExercise = fetchedResultsController.fetchedObjects {
hasUserExercises = UserExercise.count > 0
}
workoutDesignerTable.isHidden = !hasUserExercises
tapToAddExercise.isHidden = hasUserExercises
activityIndicatorView.stopAnimating()
}
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<UserExercise> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<UserExercise> = UserExercise.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addNewExerciseSegue" {
if let destinationViewController = segue.destination as? ExerciseEditorController {
// Configure View Controller
destinationViewController.managedObjectContext = persistentContainer.viewContext
}
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.endUpdates()
updateView()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
workoutDesignerTable.insertRows(at: [indexPath], with: .fade)
}
break;
default:
print("...")
}
}
}
You need to call context.save().

Difficulties in moving Page in swift

when I select UIButoon(selectMaghsad or selectMabda) go AircraftSearch to SelectedCity without difficulty and problem I choose one cell in selecteCity(tableviewController) go back to AircraftSearch and show data in label (labelcity) The problem is that Without that I want again go to tableViewController(selecteCity)
and alert :
A
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7f867b5a4920 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}
why ??
Where do you think the problem is?
can you help me ??
AircraftSearch
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
#IBOutlet weak var cityTectfield: UITextField!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
var tit = String()
override func viewDidLoad() {
super.viewDidLoad()
labelcity.text = tit
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func GetPassCity(){
let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
actInd.center = self.view.center
actInd.hidesWhenStopped = true
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(actInd)
actInd.startAnimating()
NSURLSession.sharedSession().dataTaskWithURL(Airurl){ ( data ,response ,error) in
if error != nil{
print("A")
print(error!)
}else{
do{
//readin data from Server
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
//save data
for post in posts{
var postCity:MabdaAndMaghsad?
if let Id = post["Id"] as? Int ,
let nameCity = post["Name"] as? String ,
let SrcOrDst = post["SrcOrDst"] as? Bool
{
postCity = MabdaAndMaghsad(ID: Id, Name: nameCity, SrcOrDst: SrcOrDst)
}
self.ScrOrDstArray.append(postCity!)
}
//===============
dispatch_async(dispatch_get_main_queue()){
actInd.stopAnimating()
self.originAndpurpose()
print(self.origin)
print("=======")
// print(self.purpose)
}
}catch let error as NSError{
print("B")
print(error)
}
}
}.resume()
}
func sendNameToPreviousVC(SelectCity: String) {
tit = SelectCity
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
SelectedCity view
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
self.delegate = VCOne
}
}
}
pic

Segue to another imageview for fullsize Image

I have a photoview controller that displays images in a table view. I am looking for help to segue to a fullsizeimageview imageview controller. I can't figure out how to do that.
import UIKit
import Parse
import ParseUI
class PhotosViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let arrSubCatData: NSMutableArray = [];
#IBOutlet weak var tblPhotos: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationItem.title = "Photos"
var tabBar : TabBarController = self.tabBarController as! TabBarController
println(tabBar.parkInfo)
self.tblPhotos.tableFooterView = UIView()
var query = PFQuery(className: "MultiImages")
query.whereKey("placeId", equalTo:tabBar.parkInfo?.valueForKey("objectId") as! String)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
self.arrSubCatData.addObjectsFromArray(objects!)
self.tblPhotos?.reloadData();
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableViewCell") as! UITableViewCell
if let file:PFFile = (self.arrSubCatData.objectAtIndex(indexPath.row).valueForKey("image") as? PFFile) {
file.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
var imgView : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView
imgView.image = UIImage(data:imageData)
}
}
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("segueToInfo", sender: indexPath.row)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrSubCatData.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
/*override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showfullsizeimage" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let detailViewController = segue.destinationViewController as! PhotoFullSizeController
detailViewController.detailItem = objects[indexPath.row]
}
}
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
My newly created fullsize image controller is like this with segue identifier "fullsizeimageview"
import UIKit
class PhotoFullSizeController: UIViewController {
#IBOutlet weak var fullImageView: UIImageView!
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.
}
}
First of all, You should add TapGesture to the imgView.
Your cellForRowIndexPath will be now as follow :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableViewCell") as! UITableViewCell
if let file:PFFile = (self.arrSubCatData.objectAtIndex(indexPath.row).valueForKey("image") as? PFFile) {
file.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
var imgView : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView
//Add Tap Gesture to the imgView
imgView.userInteractionEnabled = true;
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped"))
imgView.addGestureRecognizer(tapRecognizer)
imgView.image = UIImage(data:imageData)
}
}
}
}
return cell
}
Now write a handler for imageTapped
//When image is tapped
func imageTapped()
{
println("image tapped")
self.performSegueWithIdentifier("fullsizeimageview", sender: self)
}
And prepareForSegue will look as follow :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "fullsizeimageview")
{
let destVC = (segue.destinationViewController as? PhotoFullSizeController)!
let indexPath = self.tblPhotos.indexPathForSelectedRow() //IndexPath for selected table row
if let file:PFFile = (self.arrSubCatData.objectAtIndex(indexPath!.row).valueForKey("image") as? PFFile) {
destVC.imageFile = file
}
}
}
In your PhotoFullSizeController controller
class PhotoFullSizeController: UIViewController {
#IBOutlet weak var fullImageView: UIImageView!
var imageFile: PFFile!
override func viewDidLoad() {
super.viewDidLoad()
// Load image
self.imageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
//Set image in imageview
fullImageView.image = UIImage(data:imageData)
}
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Let me know if any issue is there. Hope this will help!