I am working on an iOS app that uses a very common Core Data based tableview to display items and when one it selected, it shows a more detailed view, much like the Contacts app. The detail view itself is a programmatically generated grouped table with a custom (nib-defined) view for a header that has a picture and a name. Some of the cells in the table are custom cells that have a label name and a textbox value. In "edit" mode, the editable table cells (and the name in the header) have .clearButtonMode set to UITextFieldViewModeAlways to show that they are editable.
I am currently using the same view controller to display the detailed information, edit the information, and add a new record to the original list.
When a new item is being added, the view controller is created modally with a custom init overload that sets a flag in the view controller to indicate that it is adding the record. This allows it to start in edit mode and if edit mode is left, the model view is dropped away. The right menubar button is the usual Edit/Done, and the left one is a cancel button. When an existing item is being edited, the left button (normal back button) is replaced with a cancel button.
I am starting to have second thoughts as to whether or not having one view controller handle three different modes is the way to go. There are few issues that I am not sure how to handle.
1) How do I tell if edit mode is left by hitting "Done"? Is there an action for it? If cancel is hit, the action either dismisses itself (add mode) or restores the previous values leaves edit mode. I suppose I could put a check in my setEditing override to handle it, but it seems that there should be a better way.
2) When edit mode is entered and I set the editable text fields to UITextFieldViewModeAlways, is there a way to animate the appearance of the 'X' buttons so that they fade in with the editing indicators on the regular cells?
Are there easy solutions to these problems or is my 3-in-1 view controller a bad idea? It doesn't seem right to remake the same view for different modes, but having multiple modes for a view controller seems to be a bit of a hassle.
jorj
I like the 3-in-1 approach and use it all the time. There are lots of advantages: one xib, one view controller, one simple protocol between the list and detail view controllers. Yes, there are a few more checks like if (self.editing) ... but I like that better than more view controllers and xibs.
To help with adding I expose a BOOL that the delegate can set.
#property (nonatomic) BOOL adding;
1) The built-in editButtonItem does not allow you to intercept it before setEditing:animated: This is problematic when you are doing data validation after Done is tapped. For that reason I rarely use editButtonItem and use my own Edit, Done, and Cancel buttons with their own action methods. See below.
2) For this I like UITableView's reloadSections:withRowAnimation. It might work in your case.
- (void)edit:(id)sender
{
self.editing = YES;
}
- (void)done:(id)sender
{
// data validation here
if (everythingChecksOut)
{
//save here
} else {
return; //something didn't validate
}
//if control reaches here all is good
//let the delegate know what happened...
if (self.adding) {
[self.delegate didFinishAddingWithData:self.yourData];
} else {
[self.delegate didFinishEditingWithData:self.yourData];
}
self.adding = NO;
self.editing = NO;
}
- (void)cancel:(id)sender
{
[self.view endEditing:YES]; //in theory, forces the view that is editing to resign first responder
//in practise I find it doesn't work with the YES parameter and I have to use my own flag
// roll back any changes here
self.editing = NO;
if (self.adding) //let the delegate know we cancelled the add...
{
[self.delegate didCancelAdd];
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
//set your nav bar title
[self.tableview.editing = editing]; //you may or may not require this
[self.tableview reloadSections... withRowAnimation:yourChoice];
if (editing)
{
//install your Done and Cancel buttons
} else {
//remove Cancel and put the Edit button back
}
}
Then in viewDidLoad...
- (void)viewDidLoad
{
[super viewDidLoad];
//whatever else you do
if (self.adding)
{
self.editing = YES;
}
}
I haven't fully understood the questions you have raised, but here are some thoughts on structure which are probably more useful in the first instance...
It seems you are doing too much with a single UITableViewController and inevitably you will end up with lots of if statements and confusing code. I'd break it down into two separate UITableViewControllers, one to handle the main view (and any subsequent editing mode you require) and then another to handle the detail view. Either or both of these could then use nibs as you require.
Using two controllers like this will allow you to simply push the second detailViewController onto a navigation stack, rather than presenting it modally which doesn't seem like the obvious thing to do in this instance.
However, if you would prefer it to be presented modally, you could write a protocol for the detailView which sends messages in the event of 'Cancel', 'Edit' or 'Done' buttons being pushed. The first viewController could then implement the protocol and receive these events.
I hope that helps...
Related
Still fairly new to iOS. I've managed to write a basic app to display a list/table of documents. I've included:
cell.accessoryType = UITableViewCellAccessoryDetailButton;
which display a blue i within a circle button which I guess can be used to perform some sort of action.
What I'd like to do now is, upon click, to display a subsequent screen with information about the document, buttons, add, delete functions, date, file size etc...
Is this done via segue or some other method?
Being a novice I am not sure what is/are the next step(s). If I know what steps I must take in order to get to next scree(s) I can search the net for example of how to do any given step.
Thank you for your help
The accessoryButton triggers it's own delegate method, distinct from the row selection, called:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
Add that method to your delegate, and then do a vc transition. There are several ways to do that transition, most of the common ones are discussed here...
First, welcome to the iOS developing community!
In order to do this, I would use a segue to a detail view that you can design. When you select a row in your table using didSelectRowAtIndexPath, you would set an #property to the object in your array that was selected: self.selectedObject = self.tableviewarray objectAtIndex:indexPath.row; Then in the prepareForSegue method you can get the destination view controller and do destinationViewController.myObject = self.selectedObject; Now the detail view knows what object to display info for!
You'll need to implement the delegate method
-tableView:(UITableView*) didSelectRowAtIndexPath:(NSIndexPath*)
and handle the row tap in that callback accordingly.
An example would be like this:
-tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
YourObject *theModelForRow = [_itemList objectAtIndex:indexPath.row];
YourViewController *someNewViewController = [YourViewController viewControllerWithModel:theModelForRow];
[self.navigationController pushViewController:someNewViewController animated:YES];
}
I wonder if anybody can explain the difference between using a unwind segue and using delegation in the example I have below:
I have a FriendsTableViewController populated by an array of friends and another AddFriendTableViewController with a function to add a friend to the FriendsTableViewController.
This is how I send the data from my AddFriendViewController with a unwind segue:
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Check whether the Done button was tapped.
// If it wasn’t, instead of saving the friend, the method returns without doing anything else.
if (sender != self.doneButton) return;
// See whether there’s text in the text field.
if (self.nameTextField.text.length > 0) {
// If there’s text, create a new friend and give it's properties the input from the text fields.
self.friend = [[Friend alloc] initWithName:self.nameTextField.text
dateOfBirth:self.birthdayDatePicker.date
numberOfGifts:0];
}
}
This is how I add the data from the AddFriendTableViewController to the array in FriendsTableViewController with the unwind segue action:
#pragma mark - Actions
- (IBAction)unwindSegue:(UIStoryboardSegue *)segue
{
// Retrieve the source view controller, the controller that is unwinding from.
AddFriendTableViewController *soruce = [segue sourceViewController];
// Retrieve the soruce view controller’s friend object.
Friend *friend = soruce.friend;
// See whether the item exists.
// If it’s nil, either the Cancel button closed the screen or the text field had no text, so you don’t want to save the item.
if (friend != nil) {
// If it does exist, add the item to the friends array.
[self.friends addObject:friend];
// Reload the data in the table.
[self.tableView reloadData];
}
}
Now this works as I want so I hope I'm not breaking any stackoverflow rules or offending anyone, but I just wanted to know what is the difference between the way my example code is used and if the same scenario was made but with custom delegate methods for the AddFriendViewController. If some can explain it would be great!
Using an unwind segue is very similar to having a delegate, with the following advantages:
You don't need to implement any dismiss logic
You don't need to pass references up and down the navigation stack
You don't need to declare a delegate protocol
It's trivial to unwind back a number of stages in your app
The disadvantages are
Dependent on using storyboards (which may hamper reusability)
If there are a lot of them, it can lead to the same messiness as you can get in prepareForSegue with a lot of branching off identifier names
If you decide to present the view controller via some other method (not a segue) then you can't unwind back from it
The code you have looks good. I'd stick with it.
In a UIWebView, I want a certain class div element to display only one custom contextual menu entry. So that I implemented the canPerformAction:: method in the UIWebView delegate like this:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (self.webView.superview != nil) {
BOOL isMyClass=[[self.webView stringByEvaluatingJavaScriptFromString:#"window.getSelection().getRangeAt(0).startContainer.parentNode.className;"] isEqualToString:#"myClass"];
if (isMyClass) {
if (action == #selector(myAction:)) {
return YES;
} else {
return NO; // should disable any other menu items
}
}
}
return [super canPerformAction:action withSender:sender];
}
The result is quite strange: when the user selects such a myclass div, most menuItems are not displayed (cut: copy: past:...) but select: and selectAll: are still displayed (along with myAction). Under debugger, I notice that these two select/selectAll methods do not fire canPerformAction:: in the delegate... Where are these two method fired?
I think I know why you may be having problems.
I had the same question and similar frustration:
"Why are select: and selectAll: not appearing when stepping through calls to canPerformAction::?"
I then realized that the firstResponder when displaying the UIMenuController was just a container, and that this class had a member that was actually extending the UITextView class. Since the sharedMenuController interacts with the first responder in the Responder chain, implementing canPerformAction in the container skipped select and selectAll because they had already been handled by the textView member (the REAL firstResponder in this situation).
What you should do is find which object is your firstResponder when displaying the UIMenuController, find any responder objects it might own until you find the highest responder on the stack, and implement canPerformAction there.
Good Luck!
Sometimes, when application is used on the iPad device, with no connection to Xcode, the menu correctly displays only the authorized item... Sometimes not... Very erratic behaviour indeed
I have a tableview with UITextFields to build a form. I then have a button in the toolbar which launches a modal view controller to select some data which is then passed back to the tableview. However, the new data that was selected does not get refreshed into the UITextField using textField.text = valueReturnedFromModal syntax. Is there something I'm missing?
I see that the data is being returned properly from the modal so that is not the issue. I'm just having trouble forcing the UITextField to refresh with the new data. I've tried forcing a reloadData on the tableview as well.
So from the modal view, here's the code that passes data back:
- (void)doneAccountSelection:(id)sender
{
[delegate didSelectAccount:currentAccount];
[self dismissModalViewControllerAnimated:YES];
}
and here's the actual method in the delegate:
- (void)didSelectAccount:(SFAccount *)selectedAccount
{
//Ensure a valid deal exists for the account to be attached to
[self createDealObjectIfNeeded];
//Set the deal account
[self.deal setAccount:selectedAccount];
//Refresh the text fields
//Tag 3: Account Name field
UITextField *acct_name = (UITextField *) [self.view viewWithTag:3];
[acct_name setText:self.deal.account.field_acct_name_value];
//Tag 4: Account City field
UITextField *acct_city = (UITextField *) [self.view viewWithTag:4];
[acct_city setText:self.deal.account.field_acct_city_value];
//Save the context changes. A new deal gets created above if one does not exist.
if ([self saveModel]) NSLog(#"Acct object created, attached to deal successfully!");
[self.tableView reloadData];
}
Would you mind posting the code that sets the text fields data and the code that passes the data back to the table view?
Answer:
It appears that you are properly setting the data, however, you are dismissing the modal view controller after sending the delegate message. In this scenario, the table view is not even created until after the dismissModalViewControllerAnimated: has ended. Which means the textfields are NULL until the view is present. What I suggest is call
[self dismissModalViewControllerAnimated:YES];
as the first line in the didSelectAccount: delegate method. This would dismiss the modal view and then continue on with your setting the data to valid textfields as -viewWillAppear: / -viewDidAppear: would have already been called. Everything seems ok it's just the order that may be tripping you up. Although
-dismissModalViewControllerAnimated:
is passed to its parent if a view controller does not have a modal view (because it is the modal view), it seems more appropriate to call this method in the delegate method where you will eventually manipulate the view due to new data, etc.
use this after getting Value in text field:
[self.tableView ReloadData];
After some serious debugging found that self.account was being used in cellForRowAtIndexPath to set the initial UITextField values within the UITableViewCell. Then after modal selection completed, I was only updating the account reference for the deal object and not updating the self.account object.
I then added to this by creating a new method called updateTextFieldsAfterModalFinished and moved the code to update the UITextFields there. This method was then called from didSelectAccount which is the delegate method for modal view that is dismissed. Things are now working as expected and the UITextFields get updated after modal selection is finished.
To some this may sound like a daft question. I've searched around, and found little, mostly because I cannot find the appropriate search terms.
Here what I want to do is:
The application begins at view A.
View A launches view B, and view B launches view C.
Is their a way for view C to return directly back to A without dismissing itself and thus exposing B. For example a main menu button.
You can call popToRootViewControllerAnimated: if you have a UINavigationController. If you specify NO to animate it, then it will just jump back to the root without showing B first.
I have discovered a solution to my problem. Its a bit dirty, (and I''ll probably get shot down in flames for it) but works very well under tests and is very quick to implement. Here's how I did it.
In my app I have a Singleton class called GlobalVars (I use this for storing various global settings). This class holds a boolean called home_pressed and associated accessors (via synthesise). You could also store this value in the application delegate if you wish.
In every view controller with a main menu button, I wire the button to the homePressed IBAction method as follows. First setting the global homePressed boolean to YES, then dismissing the view controller in the usual way, but with NO animation.
-(IBAction) homePressed: (id) sender
{
[GlobalVars _instance].homePressed = YES;
[self dismissModalViewControllerAnimated: NO];
}//end homePressed
In every view controller except the main menu I implement the viewDidAppear method (which gets called when a view re-appears) as follows.
-(void) viewDidAppear: (Bool) animated
{
if ([GlobalVars _instance].homePressed == YES)
{
[self dismissModalViewController: NO];
}
else
{
//put normal view did appear code here/
}
}//end viewDidAppead
In the mainMenu view controller which is the root of the app, I set the global homePressed boolean to NO in its view did appear method as follows
-(void) viewDidAppear: (Bool) animated
{
if ([GlobalVars _instance].homePressed == YES)
{
[GlobalVars _instance].homePressed == NO;
}
else
{
//put normal view did appear code here/
}
}//end viewDidAppear
There, this enables me to go back to the root main menu of my app from any view further down the chain.
I was hoping to avoid this method, but its better than re-implementing my app which is what I'd have to do if I wanted use the UINavigationController solution.
Simple, took me 10 minutes to code in my 9 view app. :)
One final question I do have, would my solution be OK with the HIG?