Reusing a detail UIViewController involved in a storyboard segue - ios

I have a master/detail application running on an iPad. When in landscape mode, I have both views up side-by-side. The right/detail view controller contains an MKMapView.
The issue is that when selecting a different table cell in the left/master view controller, and essentially re-performing the segue, the entire detail view controller is reinstantiated.
This means that the MKMapView I was using loses the user's position, and essentially starts from scratch, zooming in from the country scale to the street scale.
Is there a way to determine, prior to performing the segue, whether the detail view being displayed is already the one I want, and simply providing it new data and telling it to refresh?
For example:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
segueParkName = parkNames[indexPath.row]
self.performSegueWithIdentifier("showParkDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showParkDetails" {
let controller = (segue.destinationViewController as UINavigationController).topViewController as ParkDetailsController
NSLog("Controller: \(controller)") // Different instance every time!
controller.parkName = segueParkName
}
}
I would like to either:
Somehow tell iOS that by the time prepareForSegue is reached, I'm okay with being provided a reused view controller, especially (!) if it's already displayed.
In the didSelectRowAtIndexPath method, perform a custom segue and do my own pushing. But I really like the idea of using the built-in system segues so I don't have to be specific about what I'm pushing and where. It seems more device-agnostic to use Show Detail (eg. Replace) than defining my own.

I think, in your first suggestion, it will be troublesome if not impossible to abandon the segue once you are in prepareForSegue. So I would go with your second option. But you don't need to trigger a segue at all, if the detail viewController you want is already in place. So rather than
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
segueParkName = parkNames[indexPath.row]
self.performSegueWithIdentifier("showParkDetails", sender: self)
}
you might have something like...
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
segueParkName = parkNames[indexPath.row]
self.detailViewController.parkName = segueParkName
}
This assumes that you already have a property detailViewController pointing to your detail ViewController. It also assumes that the detailViewController will always be the one you need - if necessary, check the detailViewController class to see whether it is the MKMapView you want. Finally, if setting parkName doesn't achieve everything you need (e.g. animating the change), then just implement a new method in your MkMapView and call that in place of setting parkName.
EDIT Just to expand on that, you can use:
if self.detailViewController.isKindOfClass(yourMKMapViewSubclass) {
self.detailViewController.parkName = segueParkName
}
to test whether detailViewController is indeed your MkMapView.

You can cancel a segue by implementing shouldPerformSegue however that is for the case where the park name is invalid for some reason, to prevent showing a view controller for an invalid park.
In this case the solution is use the reference to the detail controller in your master controller that the built-in master/detail template does for you. Then in prepareForSegue take the map from the old detail controller and put it on the new one.
As your app gets more complex it may no longer be suitable for the master to maintain a reference to the detail controller. For example, if you make a root controller that pushes a new master, then the master will not find the detail when the app is in portrait like the template app can. Thus in that case your class that implements the split controller delegate can also maintain the context for your master/detail (something that is initWithSplitViewController). By setting an owningContext param self on the splitViewController via a category in the init for this class, then you can access it from where you need to. E.g. setting the mapView on it from the master. And getting the mapView from it in the loadView of the detail.

Related

SWIFT: Connect UITableViewCell to two different detail view controllers

Suppose I have a SWIFT app and it contains a UIViewController with a table. The table of course has prototype UITableViewCells. The information contained in the cell can be one of two internal object types, lets say Widget and Sprocket. Widget and Sprocket are objects that derive from the same base class Thing.
My table will be a list of Things, where each Thing is either a Widget or a Sprocket. What I want to happen is that if a user selects a table cell that is a Widget, it should show a details ViewController for a Widget, ie WidgetViewController. If however the user selects a Sprocket then the app should show a SprocketViewController.
How exactly can I make this happen? My understanding is that if I go into the storyboard and click-drag to make a segue from the main VC to either WidgetViewController or SprocketViewController then that segue will occur in the app automagically, ie without me adding any code. So if I click-drag to create two such segues then I have no idea what will happen but I assume that the app will crash from trying to call both segues.
The problem I am facing is that my current app has a WidgetTableViewController with a storyboard segue to a WidgetViewController and also has a SprocketTableViewController with a storyboard segue to a SprocketViewController, but now I have to put Widgets and Sprockets into the same VC (ie ThingTableViewController) and have the app conditionally launch either WidgetViewController or SprocketViewController.
So how do I do this?
One way to do this could be:
In the tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function of your UITableViewDelegate check if the selected cell corresponds to an object Widget or an object Sprocket
Then, present the corresponding UIViewController with the necessary configuration with this code:
let vc = UIStoryboard(name: "The name of your storyboard here", bundle: nil).instantiateViewController(withIdentifier: "Your VC identifier") as! YourViewController
// pass your data and configure the viewcontroller here
navigationController?.pushViewController(vc, animated: true)
In storyboard, assign the identifier that you think is convenient to your ViewController:
Select the ViewController -> 3rd item -> Identity -> StoryboardId and check "Use Storyboard ID"
Note: Delete the segues what are you currently using
1) To configure you cells you have your DataSource. So basically you could just configure your tableView with array of structures like this.
struct ViewModel {
var type: CellType
...
}
When you tap your cell with type you could easily find what detail controller you need.
2) In didSelectRow you cold get tapped cell
let cell = tableView.cellForRow(at: indexPath)
and than just check if its is WidgetsCell or SprocketsCell

Strange behaviour during mid-swipe back

I'm experiencing a strange glitch where I can use the previous view controller before the top view controller has been dismissed.
At my main view controller I have a table view with the delegate function didSelectRowAtIndexPath. The function is below:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("commentsSegue", sender: self)
}
This works great, however if I am already showing this screen, I can select it again if I half-swipe back. This is sort of hard to explain but you can use a finger to swipe back and the other to select a cell on the main viewcontroller. This creates another segue to a new "commentsSegue". I can do this as many times as I like and it will action many segues.
I have tried to overcome this by using
if (self.presentingViewController?.presentedViewController == self) {
and also
if (self.navigationController?.topViewController.title == self.title) {
But both of these functions return the main viewcontroller as the active view controller instead of the "commentsSegue" controller.
How can I stop this behaviour from occurring?
On swipe create a Notification which check if your destination controller .isKindOfClass your current one. If not , make the segue.

Data exchange between UIViewControllers, Service and Views

Top brick problem I face every time is a passing data between component.
I can separate this problem in few sub-problems:
Do we need to pass data to views? Do we need to change model directly in view?
Can we use some service call directly from views, or we need to pass back all operation to UIViewConrtoller and only then controller will request appropriate service.
Specifying indexes instead of real models.
So the first question demonstrate case when we create UITableViewCell and pass to it data directly. So we now have ability to modify some properties of this data object. Let's say we have PlayListViewController that implement UITableView datasource. If you see bellow I set data model directly into view.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = viewController.theTableView.dequeueReusableCellWithIdentifier(String(SongTableViewCell.self)) as! SongTableViewCell
cell.song = songs[indexPath.row]
return cell
}
Second one for example, when you want to trigger something in your service directly from your SongTableViewCell without using any delegate calls. Let's say in SongTableViewCell I want to play my song and on this cell I have play button. So then it is a simple solution - I can bind cell with UIButton action touch up inside for example and invoke needed operation in my service:
#IBAction func onTappedPlayButton(sender: AnyObject)
{
MusicService.playSong(song)
}
But usually I do another things. I store delegate instance in my cell that pass back any action to a controller and controller decides what to do:
#IBAction func onTappedPlayButton(sender: AnyObject)
{
delegate?.didTappedPlayButton()
}
In this case SongTableViewCell looks like this:
class SongTableViewCell: UITabeViewCell
{
weak var delegate:SongTableViewCellDelegate?
...
#IBAction func onTappedPlayButton(sender: AnyObject)
{
delegate?.didTappedPlayButton(index)
}
}
and my view controller implements this didTappedPlayButton method where it calls MusicService.playSong(song). Here is 3rd problem if we have not pushed model object into UITableviewCell then we need to say somehow to view controller that it needs to play some appropriate song from array. So I use index that I set into the UITableviewCell which is sometimes can tangle other developers. I don't know if it's better to use index or data model. I understood advantage of changeability but index say nothing for developers and data model object says a lot.
I know it's more architecture questions, but maybe we can outline some props and cons of these 3 approaches/problems.
I found a post and it says
Classes=more complexity. Values=less complexity. Not sure it can fit all my subquestion, but maybe values it much better then transit entire class.

Segue to a New Instance of the Current View Controller

I have a storyboard view embedded in a navigation controller that displays a record from a database along with a link to view a related record. The related record needs to use the same view to display its data while still maintaining a navigation stack so the user can go back to the previous record. Keeping in mind that some data needs to be passed to the new viewController and the UI is composed of a tableView with each element in a row, how can this segue be accomplished?
Below is the view. If possible, please respond with any sample code in Swift.
With some inspiration from this answer and guidance by #Jassi, here is the final product:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = storyboard?.instantiateViewControllerWithIdentifier("inventoryItemDetail") as InventoryDetail
vc.fmRecordId = item["inContainerRecordId"]! //this is the data which will be passed to the new vc
self.navigationController?.pushViewController(vc, animated: true)
}
An idea-
Give the view controller an identifier. And override the below function.
prepareForSegue
In that function instantiate the view controller using the identifier you have and then pass the necessary data to that controller. And push it on navigation controller.
I hope it will work.

iOS Swift - UITableView didselectrowatindexpath crashes

First of all, let me say that this is a noobish question so please bear with me here :D. I have a tableview embedded in a navigation control and it is my main view. There is an "Add" button where I can add "things" then when that is triggered it shows the added item on the table view and also switches back to the main view controller with the code below
#IBAction func buttonAddPost_Click(sender: UIButton) {
postMgr.addPost(titleBox.text, description: descriptionBox.text, postDate: date)
self.navigationController.popToRootViewControllerAnimated(true)
}
Again the above code takes me back to the main table view controller just fine.
But when I click on a cell to take me to a more detailed view, the app crashes. Here is the code
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let listingPage = self.storyboard.instantiateViewControllerIdentifier("listingPage") as PostListingTableViewController
self.navigationController.pushViewController(listingPage, animated: true)
}
"listingPage" is the storyboard ID for the new view controller I'm trying to go to. I have used the above technique a few times somewhere else and worked just fine but I'm not sure what's wrong here.
Error I get:
Thread 1
0 swift_dynamicCast and it highlights 0x1d7150: pushl %ebp Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT)
1
2 Exchange.PostlistTableViewController ([app name].[class name]) and it highlights the didselectrowatindexpath
.
.
.
Please help...
KM
The exception tells you what the problem is - You are casting the view controller as PostListingTableViewController but the object type that is returned is PostlistTableViewController so the cast generates an exception.
You need to determine what the correct class name is and either update your storyboard or your didSelectRowAtIndexPath so that they are consistent - either Postlist or PostListing.

Resources