Sending data from one uiviewcontroller to another navigationcontroller using present modally - uiviewcontroller

I am new to swift i am using storyboard and have used navigationcontrollers to connect from one viewcontroller to another. I want to send the name of the image clicked to the next viewcontroller which is connected modally in storyboard from the imageView. I searched lot about transferring data from oneviewcontroller to another viewcontroller connected with navigationcontroller modally but no solution was available. Please let me know if any of the code is required as i dont know how to go ahead with it. I know this might be silliest question but posting this after searching a lot on net.
EDIT according to #uraimo reply.
Do i need to provide name to every segue i created on storyboard?.
I have 2 fixed images on viewcontrollerA and i have placed a uibutton with transparent background and no text on each of them and then ctrl drag to navigation controller of viewcontrollerB for presenting modally and unwinding the backbutton i.e. UIBarButtonItem to viewcontrollerA by ctrl drag the back button of viewcontrollerB to exit of the viewcontrollerB and unwinding it.
This is how i have created navigation from any of the image click out of 3 images of viewcontrollerA to viewcontrollerB and back to viewcontrollerA on back button click of viewcontrollerB.
Please let me know if i am doing anything wrong and will your prepareForSegue code be useful in accomplishing my task.

Basically, both using IB or when you do it programmatically, you have to configure your new viewcontroller with all the data it needs before the segue is performed (or the controller is presented via code).
In your case, just set the image name (your custom view controller class YourViewController should have a specific String property to hold this value) overriding prepareForSegue in the current view controller class:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "yourModalSegueIdentifier" {
let imgName= (sender as! UIImageView)
let destination = segue.destinationViewController as UINavigationController
let yourController = destination.topViewController as YourViewController
yourController.imageName= <name here>
}
}
This solves the passing data question.
But in your case, you need the name of the clicked image, and that can be only obtained adding a click event through a UIGestureRecognizer to the UIImageView.
So, you'll need a uigesturerecognized that on click will perform the segue you've created. And also, you will not be able to get the name of the image asset (the one you use the creating an UIImage using imageNamed:) because it's not available anymore, and yo'll have to use the accessibilityIdentifier.
This makes everything way more complicated, it seems it could be done for the most part graphically here and here(but it's not really clear how to do it), but it's usually done via code.
Simplifying it a bit using a global variable:
var currentImage = ""
func viewDidLoad(){
...
...
let aTap = UITapGestureRecognizer(target: self, action: Selector("imageTapped:"))
aTap.numberOfTapsRequired = 1
//For every image, configure it with recognizer and accessibilityId:
firstImage.userInteractionEnabled = true
firstImage.addGestureRecognizer(aTap)
firstImage.accessibilityIdentifier = "firsImage"
...
}
func imageTapped(recognizer:UITapGestureRecognizer) {
let imageView = recognizer.view as! UIImageView
currentImage = imageView.accessibilityIdentifier
self.performSegueWithIdentifier("yourModalSegueIdentifier", sender: self)
}
And change this:
yourController.imageName= <name here>
to this:
yourController.imageName= currentImage
Update:
Do i need to provide name to every segue i created on storyboard?
Yes, it's the only way to identify them, every UIStoryboardSegue has an identifier. But remember, segues are not the only way to go from a controller to another, if you do it completely programmatically (no segues) you usually call "presentViewController". Segues are a storyboard concept.
Again, regarding the segue name/identifier, you didn't need it until now because you never referenced that segue from your code, you need it for both prepareForSegue and performSegueWithIdentifier. Just select the segue and give it a name on the right inspector pane.
The structure you describe seems ok, the only thing it's that i'm not so sure that the UIButtons are really needed, try with a modal segue from the imageview or directly from the viewcontroller to the destination view controller.
Update 2:
If you are starting and need a free course that will teach you the basics and also make you build a few interesting ios apps i recommend hackingwithswift.

check out how I did this
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch(segue.identifier ?? "") {
case "AddItem":
let destination = segue.destination as? UINavigationController
guard let itemViewController = destination?.topViewController as? ItemViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
itemViewController.collection = collection
case "EditCollection":
guard let collectionViewController = segue.destination as? EditCollectionViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
collectionViewController.collection = collection
default:
fatalError("Unexpected Segue Identifier; \(segue.identifier)")
}
}

Related

Swipe from UITableView to UIButton via UIFocusGuide not working

I’m having trouble swiping right to move focus from a UITableView to a UIButton that is to the right and below the tableview. I’ve set up a UIFocusGuide and I believe I’ve got the geometry correct. (See attached screenshot, created using Pod VisualFocusGuide.)
When I use the built-in QuickLook on the UIFocusUpdateContext, it shows only the table view focus (the highlighted row in one color, and the other rows in another color), but that might be because I can only ever get focus in the table view, so perhaps that context is limited to the table.
I’ve seen a recommendation elsewhere to associate the focus guide with the button instead of the controller’s view, but that didn’t work. Out of desperation, I also tried associating the focus guide with the tableview, but still no luck.
Here are the pertinent methods. Any light anyone can shed will be appreciated! Thanks!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addLayoutGuide(focusGuide)
self.focusGuide.widthAnchor.constraint(equalTo: self.infoButton.widthAnchor).isActive = true
self.focusGuide.heightAnchor.constraint(equalTo: self.tableView.heightAnchor).isActive = true
self.focusGuide.topAnchor.constraint(equalTo: self.tableView.topAnchor).isActive = true
self.focusGuide.leftAnchor.constraint(equalTo: self.infoButton.leftAnchor).isActive = true
self.focusGuide.preferredFocusEnvironments = [self.infoButton]
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
guard let nextFocusedView = context.nextFocusedView else { return }
// When the focus engine focuses on the focus guide, we can programmatically tell it which element should be focused next.
switch nextFocusedView {
case self.tableView:
self.focusGuide.preferredFocusEnvironments = [self.infoButton]
case self.infoButton:
self.focusGuide.preferredFocusEnvironments = [self.tableView]
default:
self.focusGuide.preferredFocusEnvironments = []
}
}
I've just gotten this to work. I added another focus guide below the table view, to the left of the button. I sized it to be the width of the tableview and the height of the button. I made its preferredFocusEnvironment the tableView. But that in itself wasn't enough. I then removed the didUpdateFocus method, and left and right swiping started working! Here's the resulting code:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addLayoutGuide(focusGuide1)
self.focusGuide1.topAnchor.constraint(equalTo: self.tableView.topAnchor).isActive = true
self.focusGuide1.leftAnchor.constraint(equalTo: self.infoButton.leftAnchor).isActive = true
self.focusGuide1.heightAnchor.constraint(equalTo: self.tableView.heightAnchor).isActive = true
self.focusGuide1.widthAnchor.constraint(equalTo: self.infoButton.widthAnchor).isActive = true
self.focusGuide1.preferredFocusEnvironments = [self.infoButton]
self.view.addLayoutGuide(focusGuide2)
self.focusGuide2.topAnchor.constraint(equalTo: self.infoButton.topAnchor).isActive = true
self.focusGuide2.leftAnchor.constraint(equalTo: self.tableView.leftAnchor).isActive = true
self.focusGuide2.heightAnchor.constraint(equalTo: self.infoButton.heightAnchor).isActive = true
self.focusGuide2.widthAnchor.constraint(equalTo: self.tableView.widthAnchor).isActive = true
self.focusGuide2.preferredFocusEnvironments = [self.tableView]
}

UINavigationController disappears when I switch to a different tab while UISearchController is visible

In my app I have a UITabBarController with several UINavigationController's. I am trying to add a search feature like in Apple's Music app, in which a search icon appears in every UIViewController's navigatonItem. When this icon is tapped, a UISearchController is presented.
The problem I am facing is that if I present the UISearchController and switch to a different tab (before typing anything in the UISearchController's searchBar), when I come back to that tab the UINavigationController is not visible anymore. Even if I cancel the search, the UISearchController is dismissed but I cannot see my original UINavigationController. If I do type something into the search bar before switching to a different bar and back, the search results remain always visible but when I dismiss the UISearchController my UINavigationController does not show up. I can only see the UITabBarController's tabBar and everything else completely white.
However, if once the UISearchController has been dismissed, if I go to another tab and then back to the original one, the UINavigationController appears again.
Here's the code for my UIViewController subclass:
let searchResultsController = SearchResultsController()
var searchController: UISearchController!
var searchButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: Selector("showSearch:"))
navigationItem.rightBarButtonItem = searchButton
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
}
func showSearch(sender: AnyObject? = nil) {
presentViewController(searchController, animated: true, completion: nil)
}

How to set UIWebView initial position?

How to set the initial focus in a HTML page using UIWebView. For example, below is the HTML page. If i load this in UIWebView, it shows from (0,0) coordinates of a HTML view. But i want to change the starting position as described in the below image. I tried to change the offset, but no use.
webView.scrollView.contentOffset = CGPointMake(100, 100).
You probably shouldn't hard code this because for one reason, it's hard-coded. If google, or whatever website you want to display alters their layout your positions will be obsolete. And you will have to resubmit your entire app just to off-set this.
My recommendation is use auto layout and 'scales page to fit' for the UIWebView.
But your code is accurate. Make sure you put it in webViewDidFinishLoad: or viewDidLoad and your UIWebViewDelegate & UIScrollViewDelegate are added to your header file and called in your implementation file :
self.webView.delegate = self;
self.webView.scrollView.delegate = self;
Place the UIWebView into a subview. A generic UIView will work.
When instantiating the UIWebView, give it screen bounds with a slightly lower width than the containing UIView. Weird, I know.
Set the UIWebView's contentOffset in the webViewDidFinishLoad method of your UIWebViewDelegate
The following code works for me, in Xcode 6.1.1. To test, just make this ViewController class the root view controller for your app:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
override func loadView () {
let screenBounds : CGRect = UIScreen.mainScreen().bounds
var slimmerBounds : CGRect = UIScreen.mainScreen().bounds
slimmerBounds.size.width = slimmerBounds.size.width - 1
let webView = UIWebView(frame: slimmerBounds)
let url = NSURL (string: "http://google.com/")
let req = NSURLRequest(URL: url!)
webView.loadRequest(req)
webView.delegate = self;
let contentView = UIView(frame: screenBounds)
contentView.addSubview(webView)
self.view = contentView
}
func webViewDidFinishLoad(webView: UIWebView) {
webView.scrollView.contentOffset = CGPointMake(0, 100)
webView.bounds = UIScreen.mainScreen().bounds
}
}
By the way ... this will set the initial position of all URLs loaded into this Web view. If you only want to position the first page, you'll need to add some additional logic to webViewDidFinishLoad

How to get object referece of UIPickerView when it create through html select tag

I have a UIWebview contains a html "select" tag, which is shown as a on the screen.
When I click the dropdown, the UIWebview brings up a UIWebSelectSinglePicker View automatically, which is shown as .
I want to change the picker view background color and text color. How can I achieve this goal?
I tried to listen on UIKeyboardWillShowNotification event, but at that moment, this view has not been created.
Thanks in advance for any helps.
I managed to resolve the issue myself.
If someone also want to change the UIPickView on the fly, please take a look:
First, add a listener on UIKeyboardWillShowNotification event.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(_pickerViewWillBeShown:) name:UIKeyboardWillShowNotification object:nil];
Second, when notification fired, call change background color method after delay. <-- This is very important, if call method without delay, the pickview does not exist at that moment.
- (void)_pickerViewWillBeShown:(NSNotification*)aNotification {
[self performSelector:#selector(_resetPickerViewBackgroundAfterDelay) withObject:nil afterDelay:0];
}
Third, go through the UIApplication windows and find out pickerView. And you can change what ever you want for pickerView.
-(void)_resetPickerViewBackgroundAfterDelay
{
UIPickerView *pickerView = nil;
for (UIWindow *uiWindow in [[UIApplication sharedApplication] windows]) {
for (UIView *uiView in [uiWindow subviews]) {
pickerView = [self _findPickerView:uiView];
}
}
if (pickerView){
[pickerView setBackgroundColor:UIColorFromRGB(0x00FF00)];
}
}
(UIPickerView *) _findPickerView:(UIView *)uiView {
if ([uiView isKindOfClass:[UIPickerView class]] ){
return (UIPickerView*) uiView;
}
if ([uiView subviews].count > 0) {
for (UIView *subview in [uiView subviews]){
UIPickerView* view = [self _findPickerView:subview];
if (view)
return view;
}
}
return nil;
}
Hope it will help.
I believe I've come up with an alternate solution to this problem. There are certain circumstances with the other solution proposed where the label colours appear incorrect (using the system default instead of the overridden colour). This happens while scrolling the list of items.
In order to prevent this from happening, we can make use of method swizzling to fix the label colours at their source (rather than patching them after they're already created).
The UIWebSelectSinglePicker is shown (as you've stated) which implements the UIPickerViewDelegate protocol. This protocol takes care of providing the NSAttributedString instances which are shown in the picker view via the - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component method. By swizzling the implementation with our own, we can override what the labels look like.
To do this, I defined a category on UIPickerView:
#implementation UIPickerView (LabelColourOverride)
- (NSAttributedString *)overridePickerView:(UIPickerView *)pickerView
attributedTitleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
// Get the original title
NSMutableAttributedString* title =
(NSMutableAttributedString*)[self overridePickerView:pickerView
attributedTitleForRow:row
forComponent:component];
// Modify any attributes you like. The following changes the text colour.
[title setAttributes:#{NSForegroundColorAttributeName : [UIColor redColor]}
range:NSMakeRange(0, title.length)];
// You can also conveniently change the background of the picker as well.
// Multiple calls to set backgroundColor doesn't seem to slow the use of
// the picker, but you could just as easily do a check before setting the
// colour to see if it's needed.
pickerView.backgroundColor = [UIColor yellowColor];
return title;
}
#end
Then using method swizzling (see this answer for reference) we swap the implementations:
[Swizzle swizzleClass:NSClassFromString(#"UIWebSelectSinglePicker")
method:#selector(pickerView:attributedTitleForRow:forComponent:)
forClass:[UIPickerView class]
method:#selector(overridePickerView:attributedTitleForRow:forComponent:)];
This is the Swizzle implementation I developed based off the link above.
#implementation Swizzle
+ (void)swizzleClass:(Class)originalClass
method:(SEL)originalSelector
forClass:(Class)overrideClass
method:(SEL)overrideSelector
{
Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
Method overrideMethod = class_getInstanceMethod(overrideClass, overrideSelector);
if (class_addMethod(originalClass,
originalSelector,
method_getImplementation(overrideMethod),
method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(originalClass,
overrideSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, overrideMethod);
}
}
#end
The result of this is that when a label is requested, our override function is called, which calls the original function, which conveniently happens to return us a mutable NSAttributedString that we can modify in anyway we want. We could completely replace the return value if we wanted to and just keep the text. Find the list of attributes you can change here.
This solution allows you to globally change all the Picker views in the app with a single call removing the need to register notifications for every view controller where this code is needed (or defining a base class to do the same).

how to find current loaded viewcontroller?

I have an tabBarController app with 2 tabBarItems.
each viewControllers contains tableView.
On didSelectRowAtIndexPath i am loading the detailview with this lines of code:
detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController_iPad" bundle:[NSBundle mainBundle]];
detailViewController.selectedDetail = [selectedDetail valueForKey:#"cardText"];
detailViewController.selectedCardTitle2 = [selectedCardTitle valueForKey:#"cardTitle"];
detailViewController.selectedRow2 = [self.tableViewInbox indexPathForSelectedRow];
detailViewController.detailCardsArray = allCards;
detailViewController.detailAllFetchedCards = allFetchedCards;
detailViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[inboxViewController presentModalViewController:detailViewController animated:YES];
Problem is, when detailView is loaded(is the actual shown viewController) and i change to the other tabBarItem, the detailView DOES NOT DISMISS. That means, that i cant load the detailView again, if didSelectRowAtIndexPath is called.
In my AppDelegate i have the method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
In this method i will check up, if the detailView is the actual shown viewController.
And if it is, and the tabBarItem changes, THEN dismiss the DetailView.
Now my question is: How can I CHECK, if the detailView is loaded (current shown view) or not?
The documentation tells us that the detailView becomes a child of the presenting view. The presenting view controller will have it's modalViewController property updated to point to the presented view. Also, the modal view's parentViewController will be updated to point to the presenting view.
So, you could check these properties to see whether or not the modal view is displayed or not.