I have gesture recognisers set up on my table view.
Swipe to the right and the accessory changes to an image of a tick
Swipe to the left and is changes to a chevron image
If a cell is tapped, it loads a local HTML file.
If you swipe to the right, the tick appears as it should. However, if you then tap a cell to view a HTML file and come back to the table view, the image reverts to the chevron.
What's the best way to ensure the tick stays as it should?
EDIT
Further code:
From 'viewDidLoad':
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSwipeRight:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.tableView addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSwipeLeft:)];
//recognizer.delegate = self;
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.tableView addGestureRecognizer:recognizer];
- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
//Get location of the swipe
CGPoint location = [gestureRecognizer locationInView:self.tableView];
//Get the corresponding index path within the table view
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
//Check if index path is valid
if(indexPath)
{
//Get the cell out of the table view
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//Update the cell or model
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"disclosure.png"]];
}
}
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gestureRecognizer
{
CGPoint location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
if(indexPath)
{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
// cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"MFGCell";
MFGCell *cell = (MFGCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MFGCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.itemTitle.text = [item objectAtIndex:indexPath.row];
cell.itemDescription.text = [description objectAtIndex:indexPath.row];
cell.itemImageView.image = [UIImage imageNamed:[icons objectAtIndex:indexPath.row]];
return cell;
}
In reaction to the user's swipe you should store the user's choice (e.g. in a private instance variable of type NSMutableArray). When the user comes back to the table view you can then reuse the information in your tableView:cellForRowAtIndexPath: to setup the cell with the correct accessory style.
Property declaration:
#property(nonatomic, retain) NSMutableArray* _accessoryStyle;
Synthesize the property. Then add this snippet to the bottom of handleSwipeLeft: to store the user's choice:
- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
[...]
NSNumber* number = [numberWithInt:0];
[_accessoryStyle replaceObjectAtIndex:indexPath.row withObject:number];
}
Add a similar snippet to the bottom of handleSwipeRight::
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gestureRecognizer
{
[...]
NSNumber* number = [numberWithInt:1];
[_accessoryStyle replaceObjectAtIndex:indexPath.row withObject:number];
}
In tableView:cellForRowAtIndexPath::
NSString* accessoryImageName;
NSNumber* number = [_accessoryStyle objectAtIndex:indexPath.row];
switch ([number intValue])
{
case 0:
accessoryImageName = #"disclosure.png";
break;
case 1:
accessoryImageName = #"tick.png";
break;
default:
// replace with your error handling code
return nil;
}
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:accessoryImageName]];
For all this to work you need to initialize the _accessoryStyle array with the same number of elements that you expect your table view to have cells. For instance, in your view controller's viewDidLoad:
- (void) viewDidLoad
{
[super viewDidLoad];
self._accessoryStyle = [NSMutableArray arrayWithCapacity:0];
NSNumber* defaultAccessoryStyle = [numberWithInt:0];
int numberOfRows = 17; // get the real number from somewhere
for (int index = 0; index < numberOfCells; ++index)
[_accessoryStyle addObject:defaultAccessoryStyle];
}
And to balance this you need to add
- (void) viewDidUnload
{
[super viewDidUnload];
self._accessoryStyle = nil;
}
There is still much room for improvement:
Find better variable names
Use an enumeration for the different styles instead of just hardcoded numbers 0 and 1
Do not allocate a new UIImageView for each table view cell, just allocate two of them and use the right one depending on the accessory style
For your problem, there is an underlying logic issue because there is either a swipe left event firing when it should not or the views are just being unloaded and resetting to default. See if you can log when the events fire; otherwise the state of the view should be preserved. Also what I would do is add an extra state variable like int currentCellState that you change when you enter your different states to keep track of your states. Then in your viewDIdLoad make sure that all your data and your view are in sync, ie the value of currentCellState matches the state of your view.
The best way to do this is to put the images/buttons you have in an array, and each time the view loads it shows the item which index is selected..
in order to do this, the swipeMethode should be modified to something like this
-(void)swipeMethod: (UISwipeGestureRecognizer *) sender
{
if(sender.direction ==
UISwipeGestureRecognizerDirectionLeft && index < [myArray count]){
[self setSelectedIndex:index+1 animated:YES];
index++;
}else if (sender.direction == UISwipeGestureRecognizerDirectionRight && index > 0) {
[self setSelectedIndex:index-1 animated:YES];
index--;
}else {
return;
}
}
in the viewDidLoad add this code:
leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeMethod:)];
[leftRecognizer setDirection: UISwipeGestureRecognizerDirectionLeft];
[self.tableView addGestureRecognizer:leftRecognizer];
rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeMethod:)];
[rightRecognizer setDirection: UISwipeGestureRecognizerDirectionRight];
[self.tableView addGestureRecognizer:rightRecognizer];
Related
In my UITable view, i want to be able to switch the positions of two cells when you drag one on to the other. I have already completed this task. The only problem is that when you try to drag one over the other, all the rows that follow shift down to make room for the new one. I do not want this, I want the cells to essentially stay visually static when you are dragging the first cell around. Any ideas?
Thanks,
Mitch
I think you can do this with some trickery, which is after all, how Apple does a lot of its animations.
Start with a UIViewController with a table view as a subview
Add a pan gesture recognizer to the main view (you'll have to implement shouldRecognizeSimultaneouslyWithGestureRecognizer: and return YES, so it will work with the table view's own gesture recognizers)
When you start to drag, create a snapshot view of the cell you started the drag over, and add it as a subview of the main view. You'll probably want to disable the table view's scrolling at this point also.
Drag that snapshot view using the pan gesture recognizer's translationInView property
When you drop the view, delete the snapshot view, and update the table's data source to show the data in the new order you created with the move.
I haven't tried all of this yet (but I've used some elements of it in other projects), but I think this should give you a start on what you're trying to achieve. There are some more details to work out for sure -- what do you want to see in the spot from where you dragged the cell? A blank space? What do you want to see when the dragged view is dropped?
After Edit:
This is what I have so far, and it works pretty well. In the storyboard, I have a UITableViewController with two cell prototypes, both basic types. The one whose identifier is "Blank" just has no text in its label. The tableviewController is embedded in a navigation controller, and I've added a button to the navigation bar with the initial title of "Drag" -- this button is connected to the toggleDragging method.
#interface TableController ()
#property (strong,nonatomic) NSMutableArray *theData;
#property (strong,nonatomic) UIPanGestureRecognizer *panner;
#property (strong,nonatomic) UIView *cellSnapshotView;
#property (strong,nonatomic) NSIndexPath *draggingCellIndexPath;
#end
#implementation TableController
- (void)viewDidLoad {
[super viewDidLoad];
self.panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(moveCellImage:)];
[self.tableView addGestureRecognizer:self.panner];
self.panner.enabled = NO;
self.panner.delegate = self;
self.draggingCellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:0];
self.theData = [#[#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",#"Black",#"Brown",#"Red",#"Orange",#"Yellow",#"Green",#"Blue",#"Violet",#"Gray",#"White"] mutableCopy];
}
-(IBAction)toggleDragging:(UIBarButtonItem *)sender {
if ([sender.title isEqualToString:#"Drag"]) {
self.panner.enabled = YES;
sender.title = #"Scroll";
}else{
self.panner.enabled = NO;
sender.title = #"Drag";
self.tableView.scrollEnabled = YES;
}
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(IBAction)moveCellImage:(UIPanGestureRecognizer *)panner {
if (! self.cellSnapshotView) {
CGPoint loc = [panner locationInView:self.tableView];
self.draggingCellIndexPath = [self.tableView indexPathForRowAtPoint:loc];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.draggingCellIndexPath];
self.cellSnapshotView = [cell snapshotViewAfterScreenUpdates:YES];
self.cellSnapshotView.alpha = 0.8;
self.cellSnapshotView.layer.borderColor = [UIColor redColor].CGColor;
self.cellSnapshotView.layer.borderWidth = 1;
self.cellSnapshotView.frame = cell.frame;
[self.tableView addSubview:self.cellSnapshotView];
self.tableView.scrollEnabled = NO;
[self.tableView reloadRowsAtIndexPaths:#[self.draggingCellIndexPath] withRowAnimation:UITableViewRowAnimationNone]; // replace the cell with a blank one until the drag is over
}
CGPoint translation = [panner translationInView:self.view];
CGPoint cvCenter = self.cellSnapshotView.center;
cvCenter.x += translation.x;
cvCenter.y += translation.y;
self.cellSnapshotView.center = cvCenter;
[panner setTranslation:CGPointZero inView:self.view];
if (panner.state == UIGestureRecognizerStateEnded) {
UITableViewCell *droppedOnCell;
CGRect largestRect = CGRectZero;
for (UITableViewCell *cell in self.tableView.visibleCells) {
CGRect intersection = CGRectIntersection(cell.frame, self.cellSnapshotView.frame);
if (intersection.size.width * intersection.size.height >= largestRect.size.width * largestRect.size.height) {
largestRect = intersection;
droppedOnCell = cell;
}
}
NSIndexPath *droppedOnCellIndexPath = [self.tableView indexPathForCell:droppedOnCell];
[UIView animateWithDuration:.2 animations:^{
self.cellSnapshotView.center = droppedOnCell.center;
} completion:^(BOOL finished) {
[self.cellSnapshotView removeFromSuperview];
self.cellSnapshotView = nil;
NSIndexPath *savedDraggingCellIndexPath = self.draggingCellIndexPath;
if (![self.draggingCellIndexPath isEqual:droppedOnCellIndexPath]) {
self.draggingCellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:0];
[self.theData exchangeObjectAtIndex:savedDraggingCellIndexPath.row withObjectAtIndex:droppedOnCellIndexPath.row];
[self.tableView reloadRowsAtIndexPaths:#[savedDraggingCellIndexPath, droppedOnCellIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}else{
self.draggingCellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:0];
[self.tableView reloadRowsAtIndexPaths:#[savedDraggingCellIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}
}];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.draggingCellIndexPath isEqual:indexPath]) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Blank" forIndexPath:indexPath];
return cell;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.theData[indexPath.row];
return cell;
}
This may be helpful, you can respond however you like to the delegate calls to achieve this effect:
https://github.com/alfiehanssen/AMHEditableTableView
Let me know if you have any questions,
I have a UITableView with some custom cells. In each cell, there is a ImageView and three labels and get the data from a string array. I have done the layout in my storyboard. The data source is a string array. This works.
Now I have insert a EditButton in the code. Now i can see the EditButton, but when I activate the edit mode the table cell will be resized, but the images and labels dont move.
Can you show me how to move the content of the cell? Who knows a tutorial with UITableView uses EditMode AND storyboards. All tutorials which I have found are based on the "old" Xcode.
Thank you very much
By the way, here is my code:
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
myData = [NSMutableArray arrayWithObjects:
#"Line1_Label1|Line1_Label2|Line1_Label3",
#"Line2_Label1|Line2_Label2|Line2_Label3",
#"Line3_Label1|Line3_Label2|Line3_Label3",
nil];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myData count];
}
// Return a cell for the table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// A cell identifier which matches our identifier in IB
static NSString *CellIdentifier = #"CellIdentifier";
// Create or reuse a cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Get the cell label using its tag and set it
NSString *currentItem = [myData objectAtIndex:indexPath.row];
NSArray *itemArray = [currentItem componentsSeparatedByString:#"|"];
UILabel *cellLabel = (UILabel *)[cell viewWithTag:1];
[cellLabel setText:itemArray[0]];
UILabel *cellLabel2 = (UILabel *)[cell viewWithTag:3];
[cellLabel2 setText:itemArray[1]];
UILabel *cellLabel3 = (UILabel *)[cell viewWithTag:4];
[cellLabel3 setText:itemArray[2]];
// get the cell imageview using its tag and set it
UIImageView *cellImage = (UIImageView *)[cell viewWithTag:2];
[cellImage setImage:[UIImage imageNamed: #"control.png"]];
return cell;
}
// Do some customisation of our new view when a table item has been selected
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure we're referring to the correct segue
if ([[segue identifier] isEqualToString:#"ShowSelectedMovie"]) {
// Get reference to the destination view controller
ItemViewController *vc = [segue destinationViewController];
// get the selected index
NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];
// Pass the name and index of our film
[vc setSelectedItem:[NSString stringWithFormat:#"%#", [myData objectAtIndex:selectedIndex]]];
[vc setSelectedIndex:selectedIndex];
}
}
#end
First of all, make an IBOutlet of the tableview in the .h and synthesize it in the .m.
Then make an action to the edit button (if you don't already have one). In the action, write:
CGRect rect = yourTableView.cell.contentView.frame;
//Do whatever changes you wish to do with the sizing of the view. origin changes placement and size changes size (duh). Line below is an example.
rect.origin.y = yourTableView.cell.contentView.frame.origin.y - 20;
yourTableView.cell.contentView.frame = rect;
This won't be animated, but I think it'll fulfill your purpose.
Overwrite the -(void)layoutSubviews{} - method of your custom UITableViewCellController.m or if you don't use a custom UITableViewCellController, try it in your UITableViewController. But I haven't tried it yet with no custom UITableViewCellController.
Something like this will do the trick:
-(void) layoutSubviews {
[super layoutSubviews];
CGFloat xPositionOfElementInTableCell = 273.0f; /* the position of the element before going into edit mode */
if (self.isEditing && !self.showingDeleteConfirmation) // if we enter editing mode but not tapped on the red minus at the moment
{
xPositionOfElementInTableCell = 241.0f;
} else if (self.isEditing && self.showingDeleteConfirmation) // after we tappet on the red minus
xPositionOfElement = 193.0f;
}
CGRect frameOfElementInTableCell = self.myElementInTableCell.frame;
frameOfElementInTableCell.origin.x = xPositionofElement;
self.myElementInTableCell.frame = frameOfElementInTableCell;
}
I hope it helps you. The idea for this code is not mine. I found it here in SO, too. Don't know where exactly.
I've got a tableview containing array of names. The search bar works perfectly filtering the names in the table view.
The problem is the didSelectRowAtIndexpath is not getting fired when clicking the search tableview cell. Could you help me out?
What is the thing that I'm missing? Should I include any special delegate to involve search tableview cell click.
Below is the image and code.
-(void)search
{
nameArray = [[NSMutableArray alloc] init];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
self.tableViewFriendsList.tableHeaderView = searchBar;
}
- (void)searchDisplayController:(UISearchDisplayController *)controller
willShowSearchResultsTableView:(UITableView *)tableView
{
[tableView setRowHeight:70];
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.tableViewFriendsList) {
NSString *friendsID =[[[self.friendsDictionary objectForKey:#"data"] objectAtIndex:indexPath.row] objectForKey:#"id"];
[[FacebookHelper sharedFacebookHelper] postOnWallWithDelegate:self andID:friendsID];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(#"I ve come here");
NSString *friendsID =[friendsListIdArray objectAtIndex:indexPath.row];
[[FacebookHelper sharedFacebookHelper] postOnWallWithDelegate:self andID:friendsID];
}
}
You forgot to set
searchController.searchResultsDelegate = self;
I do something in one of my projects that may be of assistance:
// add gesture to detect when table view is being tapped so that keyboard may be dismissed
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(dismissKeyboard)];
gestureRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:gestureRecognizer];
Moreover I am wondering why you have a search bar within a table cell. Would you mind posting a screen shot of it in your app? I am afraid you may be doing more work than is necessary.
I'm trying to make a UIBarButtonItem in the right-corner of my tableView in order to highlight and un-highlight a cell when pressed.
In less words, when users press the button, a range of cells will change their background color from white to yellow.
I'm failing to make that though, because every time i press that button the app crashes.
Here's the code i'm using to create the button:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *barButton;
barButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"high.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(colorCells:)] autorelease];
self.navigationItem.rightBarButtonItem = barButton;
}
And here to make it highlight a range of cells:
- (void) colorCells:(id)sender
{
UITableViewCell *cell;
NSString *cellValue = cell.textLabel.text;
if ([cellValue isEqual: #"textTheCellShouldBeEqualTo"]){
cell.backgroundColor = [UIColor colorWithRed:251/255.0f green:255/255.0f blue:192/255.0f alpha:1]; ;
cell.imageView.image = [UIImage imageNamed:#"hot.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
}
Where am i failing? It's supposed to work fine. Or? Am i missing something? The view is a UITableViewController.
EDIT
I modified my code like so:
- (void) colorCells:(id)sender{
UITableViewCell *cell;
NSInteger nSections = [self.tableView numberOfSections];
for (int j=0; j<nSections; j++) {
NSInteger nRows = [self.tableView numberOfRowsInSection:j];
for (int i=0; i<nRows; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:j];
cell = [self.tableView cellForRowAtIndexPath:indexPath];
}
NSString *cellValue = cell.textLabel.text;
if ([cellValue isEqual: #"textTheCellShouldBeEqualTo"] ){
cell.backgroundColor = [UIColor colorWithRed:251/255.0f green:255/255.0f blue:192/255.0f alpha:1]; ;
cell.imageView.image = [UIImage imageNamed:#"hot.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
[self.tableView reloadData];
}
}
Now it doesn't crash, but it doesn't color the background too. Any ideas?
Basing the background color off of the text in a cell seems incredibly fragile. What determines that a cell should be highlighted? Does it change? Surely, the color of the background corresponds to a specific property of the objects in your data source. A more robust approach would be to use an NSMutableIndexSet property on your class to track a set of row indexes require highlighting upon tapping the bar button.
Consider this example. I'm assuming that rowsToHighlight is an instance of NSMutableIndexSet declared in your class and that it has been populated with the indexes of rows that require highlighting. We're going to implement -tableView:willDisplayCell:forRowAtIndexPath: to adjust the background color of the cell depending if the provided index path is a member of rowsToHighlight.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.rowsToHighlight containsIndex:indexPath.row])
{
cell.backgroundColor = [UIColor yellowColor];
}
}
Then in the method that is fired by your bar button, just do an empty update block to get the table to reload with animation.
- (void)colorCells:(id)sender
{
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
Your cells won't redraw unless you tell the table view which contains them to reload them. You can do this with one of several methods. You may consider [someTableView reloadData] or one of these methods.
Also, your cell object is not the one in your table view. You might consider this:
- (void) colorCells:(id)sender
{
UITableViewCell *cell;
//grab a cell
cell = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:someRow inSection:someSection]];
NSString *cellValue = cell.textLabel.text;
if ([cellValue isEqual: #"textTheCellShouldBeEqualTo"]){
cell.backgroundColor = [UIColor colorWithRed:251/255.0f green:255/255.0f blue:192/255.0f alpha:1]; ;
cell.imageView.image = [UIImage imageNamed:#"hot.png"];
}
else {
cell.imageView.image = nil;
cell.backgroundColor = [UIColor whiteColor];
}
//perhaps you need to reload the table as well
[self.tableView reloadData];
}
I am trying to cycle/navigate through the UITextFields which I added as subviews to the UITableViewCells. However I am unable to get my nextResponder value in the textFieldShouldReturn: method. Can anyone advise me where my code went wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* PlaceholderCellIdentifier = #"PlaceholderCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
}
if (indexPath.row == 0) // first name
{
cell.textLabel.text = #"First Name:";
UITextField *tempFirstNameField = [[UITextField alloc]initWithFrame:CGRectMake(100, (44-18)/2, 320-100, 32)];
self.firstNameField = tempFirstNameField;
self.firstNameField.font = [UIFont systemFontOfSize:14];
self.firstNameField.tag = 1;
self.firstNameField.returnKeyType = UIReturnKeyNext;
self.firstNameField.delegate = self;
[tempFirstNameField release];
[cell.contentView addSubview:self.firstNameField];
}
else if (indexPath.row == 1) //last name
{
cell.textLabel.text = #"Last Name:";
UITextField *tempLastNameField = [[UITextField alloc]initWithFrame:CGRectMake(100, (44-18)/2, 320-100, 32)];
self.lastNameField = tempLastNameField;
self.lastNameField.font = [UIFont systemFontOfSize:14];
self.lastNameField.tag = 2;
self.lastNameField.returnKeyType = UIReturnKeyNext;
self.lastNameField.delegate = self;
[tempLastNameField release];
[cell.contentView addSubview:self.lastNameField];
}
return cell;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
NSLog(#"next tag %i",nextTag);
// Try to find next responder
UIResponder* nextResponder = [textField.superview.superview viewWithTag:nextTag];
//This always returns me null value
NSLog(#"next responder %#", nextResponder);
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Why do you need a tableView for that, your fields seem to be static. Use a simple scrollview if the content is larger than you screen.
To loop your fields you can :
1/ use a container view for all controls you want in your navigation loop and simply loop in your subviews NSArray
2/ best choice. Use the NSUInteger tag field to set the order in which the controls should get the focus. Begin at non-zero value because 0 is the default tag value. 10,11,12,13 and use viewWithTag: on your container view to retrieve the next control.
UITableView is not an array - it may reload or even release any cell when it's invisible.
If you would like to operate created cells - it's better to create them all, put in an array and then display them from the array. I.e. create them all before table start loading, but not in cellForRowAtIndexPath method. It may be done in ViewWillAppear, for example.
In this case all of your objects will be retained by the array and not released until you wish to.