I am trying to extract the values inputted to a textfield. The problem is these textfields are defined programmatically in a cell of a tableview.
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:(BOOL)animated];
NSUInteger numOfRows=[userControls count];
for (int i =0; i<numOfRows; i++) {
[self saveValueForRow:i];
}
}
#pragma save defaults
- (void)saveValueForRow :(int)index {
NSString *userDataString=userEntryField.text; //how to access each text field, as this currently just accesses the first one in the table
NSLog(userDataString);
[[NSUserDefaults standardUserDefaults] setObject:userDataString forKey:[controlKeys objectAtIndex:index]];
}
My instinct was to collect all the data after the view disappears. But I don't know how to access each different text field in each different cell.
You need to set the tag of cell in cellForRowAtIndexPath method as:
cell.tag = indexPath.row;
Now at the time of getting values of textField you need to first get the cell by indexPath like:
#pragma save defaults
- (void)saveValueForRow :(int)index {
NSIndexPath *nowIndex = [NSIndexPath indexPathForRow:index inSection:0]
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
NSString *userDataString = cell.userEntryField.text; //how to access each text field, as this currently just accesses the first one in the table
NSLog(userDataString);
[[NSUserDefaults standardUserDefaults] setObject:userDataString forKey:[controlKeys objectAtIndex:index]];
}
Hope this Helps!
You can set a tag for each UITextField like:
//...
textview.tag = indexPath.row;
//...
So after you can access each textField by tag. I hope this can help you.
Related
I need to get pickers value from each cell when button in that cell is clicked.Like if i click snooze button in black swan cell i should get the picker value in that cell. i am getting the row detail from
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int section = indexPath.section;
int row = indexPath.row;
NSLog(#"section: %d / row: %d", section, row);
Any help is appreciated. All the cells are custom cells.
You can get the value from the pickerssigning a tag to picker in each cell in the didSelectRowAtIndexPath like
pickerView.tag=indexPath.row;
and then in the picker delegate you can do something like following
if (pickerView.tag == 1){
//do stuff
}else (pickerView.tag == 2){
//do other stuff
}
Even you can use Switch if you want to use here too.
You can setTag to your UIButtons, with indexpath.row, if it has multi-sectioned then you can set your logic as per that, Set your UIPickerView With static Tag, which should never equal to button tag, like 999999 Tag for Pickerview.
You can set target by addTarget:action:forControlEvent method to call an instance method of the UIButton like,
//You can set it in `cellForRowAtIndexPath` method
[yourSnoozbuton addTarget:self action:#selector(selectPickerTime:) forControlEvents:UIControlEventTouchDown];
In Instance method, you can get picker value like,
-(IBAction)selectPickerTime:(UIButton *)sender {
NSIndexPath *nowIndex = [NSIndexPath indexPathForRow:sender.tag inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
UIPickerView *pickerview = [cell viewWithTag:999999];
NSString *str = [timeArray objectAtIndex:[pickerview selectedRowInComponent:0]];
//if multi sectioned, get button as per logic.
}
I have an array of dictionaries that populate a tableView as seen below
self.tableCell.usernameLabel.text = [self.loadTableArrayCopy[indexPath.row] valueForKeyPath:#"user.full_name"];
If the user likes the content of the row, they can press a save button on the cell and certain values from the dictionary are saved in Core Data.
The problem: not all values from the dictionary correspond to outlets in the uitableviewcell. If that were not the case, I could do something like this
savedItem.username = self.tableCell.usernameLabel.text
But since some values, such as thumbnails, are not displayed in the cell, I am not sure that I could do something like this since it's not associated with a cell
savedItem.thumbnail = self.thumbnail
My preferred option is to take the indexPath.row, access the dictionary at array[indexPath.row] and save by setting the managed object's properties from the dictionary. How can I get this dictionary out of the array and into a local variable so I can do something like this?
savedItem.thumbnail = [myLocalDictionary valueForKeyPath#"thumbnail"];
If you have single section, you can do it easily:
in cellForRowAtIndexPath set this:
cell.saveButton.tag = indexPath.row;
From save button event do this:
-(void)savePressed:(id)sender{
UIButton *btn = (UIButton *)sender;
int row = btn.tag; // This is your selected row.
NSDictionary *youDictionary = [array objectAtIndex:row];
}
When user tap save button then you could get the indexPath.row value.So later,
NSDictionary *saveDict = [array objectAtIndex:indexPath.row];
This way to will get dictionary and could further save it to coreData.
If not able to find indexPath.row value from button then you could do as below:-
-(void)buttonTapped:(id)sender
{
UIButton *senderBtn = (UIButton *)sender;
UITableViewCell *cell;
if (![Utilities isIPhone]) {
if ([UIDevice currentDevice].systemVersion.intValue < 7)
cell = (UITableViewCell *)[[[senderBtn superview] superview] superview];
else
cell = (UITableViewCell *)[[[[senderBtn superview] superview] superview] superview];
}
NSIndexPath *index = [advancedSearchTable indexPathForCell:cell];
}
When save is tapped you could add above lines and find out index(indexPath). Later, use index to get dictionary from array.
I have a table that imports the address book contacts and displays the image, contact name and a checkbox, i've customized my cell with image, label and a button which serves as a checkmark. I'm successfully able to display all contacts and the checkmark also works fine for individual cells, but i'm having trouble implementing select all functionality that will put all the button in the table in selected state and clicking it again will deselect it all. This is what I have done so far.
//This is the class for my custom cell
#import "InviteFriendsCell.h"
#implementation InviteFriendsCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
//This is my checkmark button
-(IBAction)onAddTouched:(id)sender
{
UIButton *addButton = (UIButton *)sender;
[addButton setSelected:![addButton isSelected]];
}
#end
//This is my tableview display code in FriendListViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"friendsCell";
InviteFriendsCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"InviteFriendsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// Configure the cell...
NSUInteger row = 0;
NSUInteger sect = indexPath.section;
for (NSUInteger i = 0; i < sect; ++ i)
row += [self tableView:tableView numberOfRowsInSection:i];
row += indexPath.row;
cell.thumbImage.layer.cornerRadius=25;
cell.thumbImage.clipsToBounds=YES;
cell.thumbImage.image=nil;
self.persons = CFArrayGetValueAtIndex(self.contactAdd, row);
NSString *tweet=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(self.persons)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[cell.friendName setText:tweet];
if (ABPersonHasImageData(persons))
{
NSData *imgData = (__bridge NSData *) ABPersonCopyImageDataWithFormat(persons, kABPersonImageFormatThumbnail);
cell.thumbImage.image = [UIImage imageWithData:imgData];
}
else
{
cell.thumbImage.image = [UIImage imageNamed:#"name_icon.png"];
}
return cell;
}
//This is my select all button which should put checkmark to all button in tableview
- (IBAction)selectAll:(UIButton *)sender {
//This is where I need to implement the code
}
There is a similar question in stack overflow here Need to create a select all button for UITableView and add selections to an array in iOS
But here the checkmark button is created inside the tableview method, my case is different and I'm unable to implement that code. Is there a better way to do this? I'm using storyboard and xcode 5 and should work for ios 5 or above.
first create a array with boolean values
#property (retain, nonatomic) NSMutableArray *selectedArray;
Initialise your selected array based on the contact add count, better generalise it and store it into an NSArray if u are planning to expand this. Here peopelist is my NSArray
self.peopleList=(__bridge NSArray *)(self.contactAdd);
self.selectedArray=[[NSMutableArray alloc]initWithCapacity:[self.peopleList count]];
for(int i=0;i<[self.peopleList count];i++)
{
[self.selectedArray insertObject:[NSNumber numberWithBool:NO] atIndex:i];
}
In the selectAll button action use this
- (IBAction)selectAll:(UIButton *)sender {
for(int i=0;i<self.selectedArray.count;i++)
[self.selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:sender.isSelected]];
[sender setSelected:!sender.isSelected];
[yourTable reloadData];
}
You need to change your data source and your cell. contactAdd needs to know that the contact is selected (you could use a new array for this, but why would you). The cell needs to callback to the controller when the button is tapped to tell the controller about whether it's selected or not. The controller needs to update the cells to set the selected status.
Your code currently won't work properly if you have lots of cells, select some and then scroll (either other rows will show as selected or the selections will be lost depending on if your reuse identifier is configured correctly).
Also, your contactAdd is overly complex. Look at using multiple arrays (one per section) as your current indexing is complicated to maintain.
I really think that using predefined "selected" method is bad and rigid approach. So I would prefer the following solution:
Just connect touch listener to every cell and handle the Tap event. When it occurs set the cell data source "selected" and update the layout of the cell.
If you want to "select all" you should update all cell datasources to "selected" and then update the whole table (reloadData)
Note: instead of making one template and manipulating data you can also create two templates for the cell - selected and unselected one and implement custom template selector in your cell constructor.
I have a UITableView in my application where I have custom UITableViewCell which contains a UITextField. What I would like to do is get the correct index of the row when I select a particular textfield from that row. Unfortunately, I am only able to get the correct index of the row if I actually click on the row, and not when I select the textfield itself. I am implementing the <UITextFieldDelegate>, and when I select a particular UITextField, I call the method:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
int rowTest = [_table indexPathForSelectedRow].row;
int rowTest1 = [_cell.tireCodeField tag];
NSLog(#"the current row is: %d", rowTest1);
NSLog(#"and this row is: %d", rowTest);
return YES;
}
The problem is that the value for the row that I am getting is from whenever the method:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
}
get's called. It is as if there is a disconnect between the UITextField and the row in the table it resides in. Is there a way for me to select a particular textField, and get the
Is there a way for me to get the index of the row by selecting the UITextField that resides within it, instead of selecting the row itself?
Thanks in advance to all who reply.
The way this is usually done, is to give the text field a tag equal to the indexPath.row, or if you have multiple sections, some mathematical combination of the section and row (like 1000*indexPathSection + indexPath.row).
Well, assuming that the cell is the direct superview or the text field, you can directly ask for the text field's superview, cast to UITableViewCell, and then ask your instance of UITableView for the index path of that cell. Here's an example:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
UITableViewCell *cell = (UITableViewCell *)textField.superview; // cell-->textfield
//UITableViewCell *cell = (UITableViewCell *)textField.superview.superview; // cell-->contentView-->textfield
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
return YES;
}
If you're looking for a more dynamic solution that works across multiple versions of iOS, then you'll probably want to use the following quoted from #Marko Nikolovski here
// Get the cell in which the textfield is embedded
id textFieldSuper = textField;
while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) {
textFieldSuper = [textFieldSuper superview];
}
// Get that cell's index path
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textFieldSuper];
This method crawls up the superview until it encounters a UITableViewCell. This keeps the code working even when the cell's view hierarchy changes, like it did from iOS 6 to 7.
I thought I'd post this slightly (!) late answer as I was trying to do this for ages and then remember another method (which if I say so myself is one of the best ways) of getting the index path for a cell when a UIButton was tapped.
In a similar way you can get the CGPoint of the cell.
-(NSIndexPath *)indexPathForTextField:(UITextField *)textField
{
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
return [self.tableView indexPathForRowAtPoint:point];
}
-(void)textDidChangeForTextFieldInCell:(UITextField *)textField
{
NSIndexPath *indexPath = [self indexPathForTextField:textField];
// Now you can update the object at indexPath for your model!
}
I think this is far neater than relying on tags or the even yuckier method of looking at superviews!
As it seems you are working with tags,using the UITextFieldDelegate,you can declare this methods in order to select the row.
-(void)textFieldDidBeginEditing:(UITextField *)textField{
int rowTest1 = textField.tag;
[myTableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:rowTest1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
}
UITableViewCell *textFieldCell = (UITableViewCell*) [[[textfield superview]superview]superview];
NSIndexPath *indexPath = [self.editProfileTableView indexPathForCell:textFieldCell];
I'm new to IOS development and i'm trying to develop my first app.
So my problem is... I've got a UITableView with custom cells, each cell contains an UITextField. When I press a button I'd like to put each UITextField value in a NSMutableArray.
I think I've got to do something like that but I'm not sure:
NSMutableArray *playerNameArray = [[NSMutableArray alloc] init];
for (int i=0; i < nbPlayers; i++){ //nbPlayers is the number of rows in the UITableView
NSString *playerName =UITextField.text;
[playerNameArray addObject:[NSString stringWithFormat: #"%#", playerName]];
}
If someone can help me.... :)
Thanks
You need to reference the instance of your UITextField, what you're doing there is attempting to call text on the UITextField class. Something like this would probably solve your problem:
NSMutableArray *playerNameArray = [[NSMutableArray alloc] init];
for (int i=0; i < nbPlayers; i++){ //nbPlayers is the number of rows in the UITableView
MyTableViewCellSubclass *theCell = (id)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
UITextField *cellTextField = [theCell textField];
NSString *playerName = [cellTextField text];
[playerNameArray addObject:playerName];
}
The text field passed to your delegate is a subview of the cell's contentView.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
UITableViewCell *cell = (UITableViewCell*) textField.superview.superview;
NSIndexPath *txtIndPath = [self.tblPendingDeliveryData indexPathForCell:cell];
write you code here.....like
if(textField.tag == 1)
{
NSMutableDictionary *dict = [self.arrPendingDeliveryData objectAtIndex:txtIndPath.row];
[dict setObject:textField.text forKey:#"ReOrder"];
}
}
In txtIndPath you will get active textfield's indexpath. Assign the textfield tag property with necessary value. It works well for me.
Look at this thread for a similar question
UITextField in UITableViewCell Help
You should to use one of the textfield delegated method to fill the proper cell of your array
- (void)textFieldDidEndEditing:(UITextField *)textField{
}