Determining the cell from a UILongPressRecognizer for a segue - ios

I'm having a slight problem with a basic checklist app I'm building.
On a regular tap of a table view cell, I segue to my NewTaskViewController using prepare(for segue):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddTask" {
let nav = segue.destination as! UINavigationController
let newTaskVc = nav.topViewController as! NewTaskViewController
newTaskVc.delegate = self
newTaskVc.managedContext = managedContext
I also have perform a segue on a UILongPressGestureRecognizer that I added to my cell. Long pressing should segue to the same NewTaskViewController but this time adding the cell's TaskItem to its taskToEdit property
} else if segue.identifier == "EditTask" {
let nav = segue.destination as! UINavigationController
let editTaskVc = nav.topViewController as! NewTaskViewController
editTaskVc.delegate = self
editTaskVc.managedContext = managedContext
editTaskVc.taskToEdit = ?
As I'm using a UILongPressRecognizer, I'm struggling to work out how I determine the index path of the cell long-pressed so I can pass the correct item through.
Essentially, how do I identify a table view cell from a gesture recognizer?
Thanks in advance!

Well could you try something like this inside your handling function?
if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {
let touchPoint = longPressGestureRecognizer.locationInView(self.view)
if let indexPath = tableView.indexPathForRowAtPoint(touchPoint) {
// Your Stuff
}
}

Related

Downcasting Any? to UIBarButtonItem

override func prepare(for segue: UIStoryboardSegue, sender:
Any?) {
if segue.identifier == "detailSegue" {
let indexPath = tableView.indexPathForSelectedRow!
let card = cards[indexPath.row]
let detailTableViewController = segue.destination as! DetailTableViewController
detailTableViewController.card = card
detailTableViewController.picture = card.image
} else if segue.identifier == "addEditSegue" {
let addEditTableViewController = segue.destination as! AddEditTableViewController
let buttonPressed = sender as? UIBarButtonItem
if buttonPressed == cardsAddButton {
addEditTableViewController.isNewCard = true
} else {
addEditTableViewController.isNewCard = false
}
}
}
Hi, I am new to Swift. I need to perform the same segue by either tapping a UIBarButtonItem (cardsAddButton) or by tapping on cells of a UITableView. Using print statements I found that buttonPressed is nil when I tap cardsAddButton. Why? How should I check what was the sender?
You – the developer – should know who the sender of prepare(for is. There are only three possibilities:
If the segue is connected to the table view cell in Interface Builder then the sender is the UITableViewCell.
If the segue is connected to the view controller in Interface Builder then the sender is the UIViewController.
If performSegue is called in code then the sender is whatever you passed in the sender parameter (including nil).
Your code can work only if you call performSegue in the IBAction of the button and pass the button instance as sender
#IBAction func addCard(_ sender : UIBarButtonItem)
{
self.performSegue(withIdentifier:"addEditSegue", sender: sender)
}

Pass Information through TabBarController Swift

Have a Table View Controller that will pass an ID field onto a View Controller in order to retrieve detail however in between the two controllers is a Tab Bar Controller. I am unsure how I am to get the information passed between the two. Was attempting to use a Segue but the value is blank once it gets to the detail controller.
EventBarTableViewCell.swift
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEventDetail" {
if let IndexPath = self.tableView.indexPathForSelectedRow {
let controller = segue.destination as? eventDetailViewController
controller?.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
controller?.viaSegue = (events?[IndexPath.row].tradeshowID!)!
//controller?.performSegue(withIdentifier: "tradeShowID", sender: self)
//if shouldShowSearchResults {
// controller?.viaSegue = filteredArray[IndexPath.row].charterNum!
//} else {
// controller?.viaSegue = repositories[IndexPath.row].charterNum!
//}
}
}
}
eventDetailViewController.swift
var viaSegue = ""
var inTradeShowID = ""
override func viewDidLoad() {
super.viewDidLoad()
inTradeShowID = self.viaSegue
}
Could use some help.
You are segueing to a Tab Bar Controller, not to your "display" view, so you need to "drill down" so to speak:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEventDetail" {
if let IndexPath = self.tableView.indexPathForSelectedRow {
// we're segueing to a Tab Bar Controller
if let tabBarVC = segue.destination as? UITabBarController {
// get the first view controller of the Tab Bar Controller
// *that* is where you want to "pass" your data
if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController {
// either should work
controller.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
controller.viaSegue = (events?[IndexPath.row].tradeshowID!)!
} //end if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController
} //end if let tabBarVC = segue.destination as? UITabBarController
} //end if let IndexPath = self.tableView.indexPathForSelectedRow
} //end if segue.identifier == "showEventDetail"
}

Pass text to TextView via Segue

I'm trying to pass text to TextView from other ViewController:
if (segue.identifier == "HomeToDetails") {
let nav = segue.destination as! UINavigationController
let nextVC = nav.topViewController as! DetailsViewController
nextVC.infoTextView.text = "TESTING"
}
But it crashes:
fatal error: unexpectedly found nil while unwrapping an Optional value
setting text on UITextField of DestinationViewController is not possible in the prepareForSegue:sender, because all view components of the recently allocated controller are not initialized before the view is loaded (at this time, they are all nil), they only will be when the DestinationViewController view is loaded.
You need to use optional variable infoString in DetailsViewController which you can set in prepareForSegue method
if (segue.identifier == "HomeToDetails") {
let nav = segue.destination as! UINavigationController
let nextVC = nav.topViewController as! DetailsViewController
nextVC.infoString = "TESTING"
}
in DetailsViewController.swift
class DetailViewController: UIViewController {
var infoString: String?
override func viewDidLoad() {
super.viewDidLoad()
if let info = infoString {
self.infoTextView.text = info
}
}
}
if value is nil and you unwrap it, then the app will crash, you should use optional binding to avoid crash.
if (segue.identifier == "HomeToDetails") {
if let nav = segue.destination as? UINavigationController { //should use optional binding to avoid crash
if let nextVC = nav.topViewController as? DetailsViewController {
nextVC.infoTextView.text = "TESTING"
}
}
}
Check this:
if (segue.identifier == "HomeToDetails") {
// get a reference to the second view controller
let secondViewController = segue.destination as! DetailsViewController
// set a variable in the second view controller with the String to pass
secondViewController.infoTextView.text = "TESTING"
}
Try this code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let nav = segue.destination as? UINavigationController {
if let nextVC = nav.topViewController as? DetailsViewController {
nextVC.infoTextView.text = "Data you want to pass"
}
}
}
this is because when you are assigning value to text view, the text view not initialized that time as viewDidLoad of next class is not called yet. So pass only string, then in viewDidLoad of next class, set the text.
You cannot pass a text directly to TextView in another view before it's created.
First ViewController:
if (segue.identifier == "HomeToDetails") {
let secondViewController = segue.destination as! DetailsViewController
secondViewController.myText = "TESTING"
}
DetailsViewController:
var myText = ""
override func viewDidLoad() {
super.viewDidLoad()
infoTextView.text = myText
}
All view components of the DetailsViewController are not initialized before the view is loaded. You can load that view before assigning values to the components of that view
Consider vC is the view controller which contains the view that you want to load. Then
if let _ = vC.view {
//Assign value here
}
Once the view is loaded, we can set the value to the components in that view. In SWIFT 3
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "HomeToDetails" {
let nav = segue.destination as! UINavigationController
let nextVC = nav.topViewController as! DetailsViewController
if let _ = nextVC.view {
nextVC.infoTextView.text = "TESTING"
}
}
}

Passing Core Data objects from DetailViewController to another View Controller

Is there a way to pass Core Data objects from DetailViewController to another View Controller to allow Editing?
From MasterViewController navigate to DetailViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let myValue = myValues[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = myValue
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
Then From DetailViewController to EditViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showEdit" {
let controller = editViewController
controller.editItem = detailItem
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
But i get nil on my object
EDIT
The edit Item is set like this on EditViewController:
var editItem: MyValues? {
didSet {
// Update the view.
self.configureView()
}
}
and the detailItem is set like this in DetailViewController:
var detailItem: MyValues? {
didSet {
// Update the view.
self.configureView()
}
}
Instead of using a property for the edit controller, use what you get from the segue.
I.e. (Assuming you're moving directly to your EditViewController): Replace...
let controller = editViewController
...with something like...
let controller = segue.destinationViewController as! EditViewController
...except you should probably test it rather than using as!.
===
Updating with my guess about how this came to be. (See comments.)
You must have created whatever editViewController points to in code someplace, which means it's not the same instance/object that is created for you as part of the segue mechanism. In other words, you had two different EditViewController objects and you were not passing data to the one that was going to be putting views on the screen.

Swift not allowing me to set variable data

I am trying to create a simple contact list app as an avenue of learning Swift. Unfortunately no matter what I try I cannot have my contacts' details display into an editable text field on a different view controller to the tableview (which contains the main contacts).
Here is the block of code that should be effecting the text fields (i am unsure of what other code to supply)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
print(object.firstName)
controller.fiName?.text = object.firstName
controller.laName?.text = object.lastName
controller.miName?.text = object.middleName
controller.aess?.text = object.address
controller.phoNumber?.text = object.phoneNumber
controller.yearBirth?.text = String(object.age)
print(controller.fiName)
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
The result of the first print line is as I expect it to be, which is the name of the contact, but the program crashes on the second print, with an 'EXC_BAD_INSTRUCTION' / fatal error: unexpectedly found nil while unwrapping and optional value.
Why can I not set the controller.fiName?.text? Thank you in advance for any help.
I guess your filName is an UILabel or UITextField right?
If you check your code in DetailViewController you will notice this line:
#IBOutlet weak var filName: UITextField!
You see the ! at the end of the line?
This means, that the variable (aka outlet) filName cannot be set at the initialization, but will be set at some point later.
Now, what you do is you init your class, and try to access that property that is not yet set at the initialization.
To get around this, create an object instance in DetailViewController, and set that instance to the selected object, and then set the label properties in the viewDidLoad function.
Something like this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.object = object
}
}
And then in the viewDidLoad of DetailViewController:
override viewDidLoad() {
fiName?.text = object.firstName
laName?.text = object.lastName
miName?.text = object.middleName
aess?.text = object.address
phoNumber?.text = object.phoneNumber
yearBirth?.text = String(object.age)
navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
navigationItem.leftItemsSupplementBackButton = true
}
You are setting the fiName label text too early, where the label hasn't been allocated yet. Instead pass through the object and then set the text in viewDidLoad of the next controller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
//pass through object:
controller.object = object
print(object)
}
}
And then in the next viewController viewDidLoad set the text:
override viewDidLoad() {
//Now set the text value here:
fiName?.text = object.firstName
}
Just object should be passed in prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
And then outlets should be setup in viewDidLoad
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
fiName?.text = detailItem.firstName
laName?.text = detailItem.lastName
miName?.text = detailItem.middleName
aess?.text = detailItem.address
phoNumber?.text = detailItem.phoneNumber
yearBirth?.text = String(detailItem.age)
}
}

Resources