editingStyleForRowAtIndexPath -- fires in iOS 5, does not fire in iOS 6 - iphone

I have simple master and detail view controllers connected with two segues, one for "show detail" and one for "add new".
"Show detail" segues to the detail view controller with setEditing:NO.
Tap "+" (add icon) segues to the detail view controller with setEditing:YES
iOS 5.1: "+" works as I expect, the detail page is in edit mode and editingStyleForRowAtIndexPath fires to show the insert and delete indicators.
iOS 6.0: the "+" makes the transition to the detail page but editingStyleForRowAtIndexPath never fires. Other code that is in setEditing:YES gets executed. didSelectRowAtIndexPath does fire (delegate = self).
Once on the detail page edit mode works as expected in both cases.
Any ideas?
// Master.m
if([[segue identifier] isEqualToString:#"NewRecipe"]) {
DetailViewController *detailViewController = [segue destinationViewController];
// stuff
detailViewController.recipe = r;
detailViewController.delegate = self;
detailViewController.editing = YES;
}
// Detail.m
-(void)setEditing:(BOOL)flag animated:(BOOL)animated {
if (flag) {
[self.tableView setEditing:flag animated:YES];
[self.tableView beginUpdates];
// the row does get added
[self.tableView insertRowsAtIndexPaths:#[pathToAdd] withRowAnimation:UITableViewRowAnimationAutomatic];
// datasource gets updated here
[self.tableView endUpdates];
....
}
}

I figured it out. I don't know why this is the fix, I hope this does not replace bad code with worse code.
Master.m
// iOS 5 -- this is OK
detailViewController.editing = YES;
For iOS 6 I needed the detailViewController to make a call to a delegate method to determine whether to setEditing:YES.
Master.m
-(BOOL)isNewRecipe {
return (_isNewRecipe == 1);
}
Detail.m
if ([self.delegate isNewRecipe]) {
[self setEditing:YES];
}

Related

MBProgressHUD activity indicator doesn't show in viewDidAppear after segue is performed

I have two UITableViewControllers A and B, and this is what I'm trying to do when I click on a table view cell in A:
Prepare to segue from A to B by setting some of B's variables from A.
Perform segue from A to B.
B appears.
Display a "Loading" activity indicator with [MBProgressHUD][1].
In a background task, retrieve data from a URL.
If an error occurs in the URL request (either no data received or non-200 status code), (a) hide activity indicator, then (b) display UIAlertView with an error message
Else, (a) Reload B's tableView with the retrieved data, then (b) Hide activity indicator
However, this is what's happening, and I don't know how to fix it:
After clicking a cell in A, B slides in from the right with an empty plain UITableView. The MBProgressHUD DOES NOT SHOW.
After a while, the tableView reloads with the retrieved data, with the MBProgressHUD appearing very briefly.
The MBProgressHUD immediately disappears.
There doesn't seem to be an error with the way the background task is performed. My problem is, how do I display the MBProgressHUD activity indicator as soon as my B view controller appears? (And actually, how come it's not showing?) Code is below.
A's prepareForSegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
B *b = (B *)[segue destinationViewController];
// Set some of B's variables here...
}
Relevant methods in B
- (void)viewDidAppear:(BOOL)animated {
[self startOver];
}
- (void)startOver {
[self displayLoadingAndDisableTableViewInteractions];
[self retrieveListings];
[self.tableView reloadData];
[self hideLoadingAndEnableTableViewInteractions];
}
- (void)displayLoadingAndDisableTableViewInteractions {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.tableView.userInteractionEnabled = NO;
}
- (void)hideLoadingAndEnableTableViewInteractions {
[MBProgressHUD hideHUDForView:self.view animated:YES];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.tableView.userInteractionEnabled = YES;
}
- (void)retrieveListings {
__block NSArray *newSearchResults;
// Perform synchronous URL request in another thread.
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
newSearchResults = [self fetchNewSearchResults];
});
// If nil was returned, there must have been some error--display a UIAlertView.
if (newSearchResults == nil) {
[[[UIAlertView alloc] initWithTitle:#"Oops!" message:#"An unknown error occurred. Try again later?" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
} else {
// Add the retrieved data to this UITableView's model. Then,
[self.tableView reloadData];
}
}
- (NSArray *)fetchNewSearchResults {
// Assemble NSMutableArray called newSearchResults from NSURLConnection data.
// Return nil if an error or a non-200 response code occurred.
return newSearchResults;
}
I think you have to call [self hideLoadingAndEnableTableViewInteractions]; after newSearchResults = [self fetchNewSearchResults]; You are retrieving data in another thread which means -startOver will continue executing after calling [self retrieveListings]; and will hide the HUD right away. Also because you are updating the display you have to make sure you are doing that on the main thread. See example
dispatch_async(dispatch_get_main_queue(), ^{
//update UI here
});
When B appears, it displays a plain and empty UITableView, but does not display the MBProgressHUD even if the task does begin in the background (and yet, the MBProgressHUD is called to show before that). Hence, my solution is to show the MBProgressHUD in viewDidLoad, which precedes viewWillAppear.
- (void)viewDidLoad {
// ...
[self displayLoadingAndDisableUI];
}
I set up two additional boolean properties to B--one in .h, called shouldStartOverUponAppearing, and one in a class extension in .m, called isLoadingAndDisabledUI. In startOver, I added the following lines:
- (void)startOver {
if (!self.isLoadingAndDisabledUI) {
[self displayLoadingAndDisabledUI];
}
}
The check is done so that startOver doesn't display another MBProgressHUD when it has already been displayed from viewDidLoad. That is because I have a third view controller, called C, that may call on B's startOver, but doesn't need to call viewDidLoad just to display the MBProgressHUD.
Also, this is how I defined viewDidAppear:
- (void)viewDidAppear:(BOOL)animated {
if (self.shouldStartOverUponAppearing) {
[self startOver];
self.shouldStartOverUponAppearing = NO;
}
}
This way, startOver will only be invoked IF B appeared from A. If B appears by pressing "Back" in C, it will do nothing and only display the old data that was there.
I think that this solution is FAR from elegant, but it works. I guess I'll just ask for a better approach in a separate SO question.
I have used a common method for MBProgressHUD.
#import "MBProgressHUD.h" in AppDelegate.h also following methods.
- (MBProgressHUD *)showGlobalProgressHUDWithTitle:(NSString *)title;
- (void)dismissGlobalHUD;
In AppDelegate.m add following methods.
- (MBProgressHUD *)showGlobalProgressHUDWithTitle:(NSString *)title {
[MBProgressHUD hideAllHUDsForView:self.window animated:YES];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
hud.labelText = title;
return hud;
}
- (void)dismissGlobalHUD {
[MBProgressHUD hideHUDForView:self.window animated:YES];
}
How to use?
AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication]delegate];
//Show Indicator
[appDel showGlobalProgressHUDWithTitle:#"Loading..."];
//Hide Indicator
[appDel dismissGlobalHUD];
Hope this helps.

UITableView editing not working

I have a button (a UINavigationBarItem) used for editing my UITableView, which only allows deletions. So when I press delete, the little red line comes up next to each cell, and I can delete each row.
When the button is pressed, the following function is called:
-(void)editButtonSelected:(id)sender {
if(self.editing)
NSLog(#"self.editing = true");
else
NSLog(#"self.editing = false");
if(self.editing) {
[super setEditing:NO animated:NO];
[tableView setEditing:NO animated:NO];
[tableView reloadData];
[leftButton setTitle:#"Delete"];
[leftButton setStyle:UIBarButtonItemStylePlain];
self.editing = false;
}
else {
[super setEditing:YES animated:YES];
[tableView setEditing:YES animated:YES];
[tableView reloadData];
[leftButton setTitle:#"Done"];
[leftButton setStyle:UIBarButtonItemStyleDone];
self.editing = true;
}
}
And it works fine. But only for a while. As soon as I introduce a new UIViewController, and then dismiss that controller, this delete function doesn't work on this main screen I have. It works fine until a new UIViewController is put on top. The button itself works fine, and the value of self.editing does get toggled between true and false correctly, but the little red lines do not show up. Why could this be happening?
I would guess that the target on your UINavigationBarItem is still set to the first view controller, not the subsequent view controllers that get pushed on the stack.

Refresh UINavigationController?

I have a UINavigationController with two ViewControllers on the stack. At a certain point in the program execution, the second view controller is visible on the screen and at that moment, I would like to replace that ViewController with another. However, it's not working. Here is my code:
UINavigationController * thisNavController = self.waitingController;
// remove the Dummy and set the new page instead
NSMutableArray * newControllers = [NSMutableArray arrayWithArray: thisNavController.viewControllers];
[newControllers replaceObjectAtIndex: ([thisNavController.viewControllers count] - 1) withObject: page];
NSLog (#"visible before: %#", [thisNavController.visibleViewController description]);
[thisNavController setViewControllers: [NSArray arrayWithArray: newControllers] animated: YES];
NSLog (#"visible after: %#", [thisNavController.visibleViewController description]);
[thisNavController.visibleViewController.view setNeedsDisplay];
The above code produces this output:
2011-05-05 13:30:22.201 myApp[3286:207] visible before: <DummyViewController: 0x4c8b4c0>
2011-05-05 13:30:22.209 myApp[3286:207] visible after: <RealViewController: 0x60173f0>
But what is shown on the screen does not change. It seems that everything works fine after I switch tabs, so it seems that it is a redrawing problem, but setNeedsDisplay does nothing and I couldn't find a method that tells the NavigationController that its viewControllers have changed.
Is there some refresh mechanism that I have to trigger to refresh the screen?
One solution would be to say add 2 (initial) view controllers when your app is started, and only allow navigation from the 2nd and 3rd ones, falling back to the 1st (root) view controller in your senario described. You never allow navigation back to this 1st view controller or from this 1st view controller to the 2nd; you see this sort of behaviour in some of Apple's apps, like iTunes and Remote - if there's no network connect the app shows a no-network connection view immediately.
So, when you want to show the 1st view controller above, you do something like:
NSArray *array = [navigationController popToRootViewControllerAnimated:NO];
Without more info about the navigation behaviour of your app I hope this helps.
Or show a modal view controller?
The problem turned out to be the fact that I was trying to replace the view controller stack before the initial transition animation for the Dummy controller has finished. This can be prevented in the following manner.
First, preserve the (eventual) delegate, set the current object as the delegate, set a flag that animation is in progress and push the new controller:
self.oldNavigationControllerDelegate = self.waitingController.navigationController.delegate;
self.waitingController.navigationController.delegate = self;
self.isAnimating = YES;
[viewController.navigationController pushViewController: [[DummyViewController alloc] init] animated: YES];
Then, implement the UIViewControllerDelegate protocol methods as follows:
#pragma mark -
#pragma mark UINavigationControllerDelegate methods
- (void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
if (navigationController == self.waitingController.navigationController)
self.isAnimating = YES;
}
- (void) navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
if (navigationController == self.waitingController.navigationController) {
self.isAnimating = NO;
if (self.readyPage != nil)
[self pageIsReady: self.readyPage]; // method to load the ready controller
}
}
After that, whenever your content/controller/download/whatever is ready, make sure that the navigation controller is no longer animating. If it is, set a flag that the page is ready. If it isn't, load the page:
if (self.isAnimating)
self.readyPage = controller;
else
[self pageIsReady: controller];
And, of course, implement the actual loading of the new stack (as usual):
- (void) pageIsReady: (UIViewController *) page {
// this method should replace the dummy that is spinning there
UINavigationController * thisNavController = self.waitingController.navigationController;
// remove the Dummy and set the new page instead
NSMutableArray * newControllers = [NSMutableArray arrayWithArray: thisNavController.viewControllers];
[newControllers replaceObjectAtIndex: ([thisNavController.viewControllers count] - 1) withObject: page];
thisNavController.viewControllers = [NSArray arrayWithArray: newControllers];
thisNavController.delegate = self.oldNavigationControllerDelegate; // restore the original delegate
// clean up
self.isAnimating = NO;
self.readyPage = nil;
self.waitingController = nil;
self.oldNavigationControllerDelegate = nil;
}
This makes everybody happy :P

Search Bar Cancel Button is Not Working

My App is having a search bar for searching records from the table view,which is populated by sqlite DB.
My problem is that when the view opens the "cancel" button is not enabled and also I cant touch on that, just like a image only.It is there but no action is with that.
when we click on that search bar text the cancel button will be changed to "done" it is enabled one.
so here is my code
this is my search bar view,see that cancel button.It is not enabled
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
//[newSearchBar setShowsCancelButton:YES animated:YES];
newSearchBar.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
NSLog(#"search begin edit") ;
//searchString = searchBar.text;
//NSLog(#"print did edit searchstring : %#", searchString) ;
for(UIView *view in [searchBar subviews])
{
//shareItemId =newSearchBar.text;
if([view isKindOfClass:[NSClassFromString(#"UINavigationButton") class]]) {
[(UIBarItem *)view setTitle:#"Done"];
}
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
NSLog(#"searchBarTextDidEndEditing:");
[searchBar resignFirstResponder];
//[self dismissModalViewControllerAnimated:YES];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
NSLog(#"searchBarSearchButtonClicked");
searchString = searchBar.text;
NSLog(#"search %#", searchBar.text);
[newSearchBar setShowsCancelButton:NO animated:YES];
[searchBar resignFirstResponder];
//[self dismissModalViewControllerAnimated:YES];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
NSLog(#" searchBarCancelButtonClicked");
[searchBar resignFirstResponder];
shareItemName =newSearchBar.text;
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
NSLog(#"searchBarShouldBeginEditing");
[newSearchBar setShowsCancelButton:YES animated:YES];
return YES;
}
These are my delegates for that
Please check my code and give me the answer. I need to enable the "Cancel" button when the view is loaded and it action will be go back to previous view
I need like this
Or else how can I add a another cancel button on exciting cancel button.so that I can enable that.please give me all the details
You need to set the UISearchDisplayController to be ACTIVE, like this:
[mySearchDisplayController setActive:YES animated:YES];
or more simply:
mySearchDisplayController.active = YES;
My guess is that Apple made the UISearchBar in a way that the cancel button is disabled if the search text field is empty or not first responder.
This is make sense because you should not use the "Cancel" button to other purpose than actually canceling the search. and since there is no search to cancel - the button is disabled.
If you still want that the button will be active immediately when the view is presented, you can call at viewWillAppear: to [mySearchBar becomeFirstResponder];
This will cause to the keyboard to appear and the button will be enabled.
And then if the user hit cancel you can intercept it to go back to the previous view. (I'm not sure if apple will like this behavior).
Sample code:
-(void) viewWillAppear : (BOOL) animated
{
[super viewWillAppear:animated];
// Make keyboard pop and enable the "Cancel" button.
[self.mySearchBar becomeFirstResponder];
}
Here's what I did to always enable the cancel button, even when the search field is not first responder.
I'm calling this method whenever I call resignFirstResponder on the search field
- (void)enableCancelButton {
for (UIView *view in self.searchBar.subviews) {
if ([view isKindOfClass:[UIButton class]]) {
[(UIButton *)view setEnabled:YES];
}
}
}
This works, but I'm not sure whether it will pass App Store verification yet, so use it at your own risk. Also, this probably only works if the cancel button is the only button you are using with the search field.
This works to reenable the cancel button as of iOS 8:
private func enableButtonsInSubviews(view: UIView) {
if let view = view as? UIButton {
view.enabled = true
}
for subview in view.subviews {
enableButtonsInSubviews(subview)
}
}

iPad not resigning responder

I have a table with 3 UITextFields added to the content views of cells (1 row per section). I have a 4th section that I insert so that I can scroll the particular field to be above the keyboard.
The problem I have (on the iPad only) is that when one of the text fields has firstResponder, it does not relinquish it when user taps on another field. Are there differences in the responder chain on an ipad? In the bellow code for my view controllers UITextFieldDelegate - textFieldShouldEndEditing does not get called when touching another field. Pressing the done button works as expected (unless another field has been touched).
Anything wrong with the code bellow?
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (!_editing++) {
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
}
// scroll to section number in the text fields tag
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:textField.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return YES;
}
- (void) textFieldDidBeginEditing:(UITextField *)textField {
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:#selector(resignFirstResponder)] autorelease];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if (_editing-- == 1) {
//
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
}
self.navigationItem.rightBarButtonItem = nil;
// do something with the text here...
return YES;
}
OK, i have found a satisfactory workaround, it seems allowing the run loop to execute before the request to animate removing a section fixes the problem. I guess this is an apple bug? For anyone else worried about this issue - i was running iOS3.2.1 on the iPad.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if (_editing == 1) {
[self performSelector:#selector(hideFinalSection) withObject:nil afterDelay:0.0f];
}
else {
_editing--;
}
self.navigationItem.rightBarButtonItem = nil;
// do something with the text here...
return YES;
}
- (void) hideFinalSection {
if (!(--_editing)) {
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
}
}