I have created a UITableView with two cells, username and password using the code below.
I have included a screenshot of the output the first time the view loads (the expected output) and the second time the view is shown (the incorrect output)
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:#"Cell"];
if( cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Login Ident"];
if (indexPath.row == 0) {
loginId = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
loginId .placeholder = #"Email address";
loginId .autocorrectionType = UITextAutocorrectionTypeNo;
[loginId setClearButtonMode:UITextFieldViewModeWhileEditing];
cell.accessoryView = loginId;
}
if (indexPath.row == 1) {
password = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
password.placeholder = #"Password";
password.secureTextEntry = YES;
password.autocorrectionType = UITextAutocorrectionTypeNo;
[password setClearButtonMode:UITextFieldViewModeWhileEditing];
cell.accessoryView = password;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
loginId.delegate = self;
password.delegate = self;
[loginId setText:[keychain objectForKey:(__bridge id)kSecAttrAccount]];
[password setText:[keychain objectForKey:(__bridge id)kSecValueData]];
[loginId addTarget:self
action:#selector(textFieldReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[password addTarget:self
action:#selector(textFieldReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[cell.contentView addSubview:loginId];
[cell.contentView addSubview:password];
}
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[_tableView reloadData];
}
My UITextField declarations
UITextField *loginId;
UITextField *password;
If anybody is able to help me out with this, I'd really appreciate it.
With changes
You should put the code where you create the text fields inside the if (cell == nil) {} since otherwise you could be adding a second textfield to a cell that's already been created previously. If that doesn't fix the issue post back.
Also, remove:
[_tableView addSubview:loginId];
[_tableView addSubview:password];
You shouldn't add views that are meant for the cells to the tableview. And instead of making it the accessoryView of the cell, add them to the contentView
[cell.contentView addSubview:loginId];
See chat below for full resolution of the issue.
Related
I'm trying to print out the value of where the user clicked in a method that is called when a user updates the value of a UISwitch in some of the cells. There are four cells that have the UISwitch set as an accessory of the cell. I already have the infrastructure in place to check against the values of calling [self.basicObjects objectAtIndex:indexPath.row], but the problem is, that no matter which cell I press, the 0 value of the NSMutableArray that contains the titles of the four cells is called.
- (void)switchChanged:(id)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"self.basicObjects value: %#", [self.basicObjects objectAtIndex:indexPath.row]);
}
As a side note, as I was looking at similar questions, it also seemed important to note that self.settingsTable is a grouped UITableView with these four cells being in section 1 (0, 1, 2). The other two sections do not contain any UISwitch as an accessory type, it's only this section, and only this one the references the switchChanged:cellForRowAtIndexPath: method.
Edit - 7:31pm
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:17.5];
if (indexPath.section == 0)
{
// change the text to standard case
// change text color
}
else if (indexPath.section == 1)
{
cell.textLabel.text = [self.basicObjects objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
self.switchProperty = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = self.switchProperty;
if ([[self.basicStatus objectAtIndex:indexPath.row] isEqual:#"YES"])
{
[self.switchProperty setOn:YES animated:YES];
[self.switchProperty addTarget:self action:#selector(switchChanged:cellForRowAtIndexPath:) forControlEvents:UIControlEventValueChanged];
}
else if ([[self.basicStatus objectAtIndex:indexPath.row] isEqual:#"NO"])
{
[self.switchProperty setOn:NO animated:YES];
[self.switchProperty addTarget:self action:#selector(switchChanged:cellForRowAtIndexPath:) forControlEvents:UIControlEventValueChanged];
}
}
else if (indexPath.section == 2)
{
cell.textLabel.text = [self.objects objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [self.objectsType objectAtIndex:indexPath.row];
cell.detailTextLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:17.5];
if ([[self.objectsStatus objectAtIndex:indexPath.row] isEqual:#"Setup"])
cell.detailTextLabel.textColor = [UIColor colorWithRed:0.298 green:0.851 blue:0.392 alpha:1]; // #4CD964 (green)
else if ([[self.objectsStatus objectAtIndex:indexPath.row] isEqual:#"Not Setup"])
cell.detailTextLabel.textColor = [UIColor colorWithRed:0.898 green:0.267 blue:0.267 alpha:1]; // #E54444 (red)
}
return cell;
}
You can't pass the indexPath in your action method that way. You can only pass the sender, and optionally, the event that triggered the action. You need to get the indexPath a different way. One common way is to give the switch a tag that's equal to the indexPath.row, and use that tag as an index into your array.
Here's a problem. You can't send the second parameter like this.
[self.switchProperty addTarget:self action:#selector(switchChanged:cellForRowAtIndexPath:) forControlEvents:UIControlEventValueChanged];
I recommend that you set a tag and use it like as below.
[self.switchProperty setTag:indexPath.row];
[self.switchProperty addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
and in switchChanged: will be...
- (void)switchChanged:(id)sender
{
NSLog(#"self.basicObjects value: %#", [self.basicObjects objectAtIndex:[sender tag]]);
}
I have been trying to figure this out for a bit. I create a custom cell in its own xib file. In my view controller I have setup a table view controller with sections. The data that is being pulled into the table View is based off a fetch request controller from some core data that I have. I set up the custom cell in the cellForRowAtIndexPath function. I am creating a label for each cell within this function and populating the label with some data from the managed object. Everything seems ok when I first run. However, when I try to scroll up and down and new cells are reused the data in the labels are placed in the wrong cells. I have seen and heard this has to do with the reuse of cells. However, have not seen much examples on correcting this issue. Below is some of the code I have in my cellForRowAtIndexPath function. Let me know if any other input may be needed. Thanks for any help.
-(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
/* do this to get unique value per cell due to sections. */
NSInteger indexForCell = indexPath.section * 1000 + indexPath.row + 1;
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
NSString *lastSession = nil;
UILabel *lastSessionLabel = nil;
if(cell == nil) {
lastSession = [managedObject valueForKey:#"last_session"];
[self.tableView registerNib:[UINib nibWithNibName:#"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
lastSessionLabel = [[UILabel alloc]initWithFrame:CGRectMake(410,55, 89, 35)];
lastSessionLabel.textAlignment = UITextAlignmentLeft;
lastSessionLabel.tag = indexForCell;
lastSessionLabel.font = [UIFont systemFontOfSize:17];
lastSessionLabel.highlighted = NO;
lastSessionLabel.backgroundColor = [UIColor clearColor];
cell.contentView.tag = indexForCell;
[cell.contentView addSubview:lastSessionLabel];
} else {
lastSessionLabel = (UILabel *)[cell viewWithTag:indexForCell];
}
if (lastSession && lastSession.length) {
lastSessionLabel.text = lastSession;
}
cell.textLabel.text = [NSString stringWithFormat:#"%#%#%#%#", #"Dr. ",
[managedObject valueForKey:#"first_name"],
#" " ,
[managedObject valueForKey:#"last_name"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.editingAccessoryType = UITableViewCellAccessoryNone;
return cell;
}
** Revised Code **
Below are the changes to code: in viewDidLoad is the following:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:#"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
}
in -(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
NSInteger indexForCell = indexPath.section * 1000 + indexPath.row + 1;
NSLog(#"index for cell: %d",indexForCell);
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
NSString *lastSession = [managedObject valueForKey:#"last_session"];
UILabel *lastSessionLabel = nil;
if(cell == nil) {
NSLog(#"Cell is nil! %#", [managedObject valueForKey:#"first_name"]);
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
}
lastSessionLabel = [[UILabel alloc]initWithFrame:CGRectMake(410,55, 89, 35)];
lastSessionLabel.textAlignment = UITextAlignmentLeft;
lastSessionLabel.tag = indexForCell;
lastSessionLabel.font = [UIFont systemFontOfSize:17];
lastSessionLabel.highlighted = NO;
lastSessionLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:lastSessionLabel];
/* Appropriate verbiage for nil last session. */
if (lastSession && lastSession.length) {
lastSessionLabel.text = lastSession;
}
return cell;
}
I am still having issues again with the label cell text changing when I scroll for different cells. I read some where about maybe having to use the prepareForReuse function for this.
You are only fetching lastSession when you create a new cell. Try putting this line before the if(cell == nil) statement.
lastSession = [managedObject valueForKey:#"last_session"];
I.e. this:
NSString *lastSession = [managedObject valueForKey:#"last_session"];
in stead of this:
NSString *lastSession = nil;
UPDATE
You are also setting the same tag for two views:
lastSessionLabel.tag = indexForCell;
...
cell.contentView.tag = indexForCell;
Based on your code sample you should only use the first line, i.e. set the tag for the lastSessionLabel
SECOND UPDATE
You should also only call registerNib: once in your view lifecycle, e.g. in viewDidLoad, not every time you need a new cell. Furthermore, you should create a new cell if cell == nil in stead of using dequeueReusableCellWithIdentifier:. E.g.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];
I have created a UITableView with two cells, username and password using the code below. I am doing this programatically as static cells can't be used in a UIViewController (where this table must reside)
I have included a screenshot of the output the first time the view loads (the expected output) and the second time the view is shown (the incorrect output)
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:#"Cell"];
if( cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Login Ident"];
if (indexPath.row == 0) {
loginId = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
loginId .placeholder = #"Email address";
loginId .autocorrectionType = UITextAutocorrectionTypeNo;
[loginId setClearButtonMode:UITextFieldViewModeWhileEditing];
cell.accessoryView = loginId;
}
if (indexPath.row == 1) {
password = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
password.placeholder = #"Password";
password.secureTextEntry = YES;
password.autocorrectionType = UITextAutocorrectionTypeNo;
[password setClearButtonMode:UITextFieldViewModeWhileEditing];
cell.accessoryView = password;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
loginId.delegate = self;
password.delegate = self;
[loginId setText:[keychain objectForKey:(__bridge id)kSecAttrAccount]];
[password setText:[keychain objectForKey:(__bridge id)kSecValueData]];
[loginId addTarget:self
action:#selector(textFieldReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[password addTarget:self
action:#selector(textFieldReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[cell.contentView addSubview:loginId];
[cell.contentView addSubview:password];
//[_tableView addSubview:loginId];
//[_tableView addSubview:password];
}
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[_tableView reloadData];
}
My UITextField declarations
UITextField *loginId;
UITextField *password;
If anybody is able to help me out with this, I'd really appreciate it.
Looks like you are having issues with your cell reuse.
Here is how I would do it:
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"Login Ident";
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:identifier];
if (nil == cell) {
// Within this if statement do any work that is not going to change over the lifetime of the cell.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
// You was setting `selectionStyle` on every run so it should be
// safe to set here once
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
const NSInteger textFieldTag = 10; // <- No special meaning, just non-zero
UITextField *textField = (UITextField *)[cell viewWithTag:textFieldTag];
// I've followed a similar pattern to the cell reuse above for creating the textfield
// This ensures that we only create a textfield once per cell and then reuse it
if (nil == textField) {
textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
textField .autocorrectionType = UITextAutocorrectionTypeNo;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.delegate = self;
textField.tag = textFieldTag;
[cell addSubview:textField];
}
// Next do any work to configure the different cells
if (indexPath.row == 0) {
textField.placeholder = #"Email address";
cell.accessoryView = loginId;
textField = textField;
loginId = textField;
} else if (indexPath.row == 1) {
textField.placeholder = #"Password";
textField.secureTextEntry = YES;
cell.accessoryView = password;
password = textField;
}
// ... rest of your work
return cell;
}
This is a issue because of the cell reusing. you need to change your cell a bit: add a textLabel in the if(cell==nil) branch, but configure it as username or password outside of the branch.
Firstly, the section:
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:#"Cell"];
if( cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Login Ident"];</code>
should be
static NSString *identifier = #"Login Ident";
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:identifier];
if( cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];</code>
Secondly, creating your text fields should be done outside the if (cell == nil) section.
I'm making UITableView without IB.
My UITableView has 2 styles UITableViewCell - first row style and other row style.
I use MTLable Class instead of UILabel.
Question:
This code's results is very strange.
First cell style and other cell style is mixed when next page scrolled.
I can't find my code's faults.
I need your advice. Thanks!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//firsT cELL
if(indexPath.row==0)
{
CGRect frame=CGRectMake(0,0,80, 60);
MTLabel *label1=[[MTLabel alloc] init];
label1.backgroundColor = [UIColor grayColor];
label1.frame=frame;
label1.text=#"123";
label1.tag = 1001;
[cell.contentView addSubview:label1];
label1.autoresizingMask = UIViewAutoresizingFlexibleTopMargin &UIViewAutoresizingFlexibleWidth & UIViewAutoresizingFlexibleLeftMargin & UIViewAutoresizingFlexibleRightMargin;
label1.contentMode = UIViewContentModeTopLeft;
[label1 setTextAlignment:MTLabelTextAlignmentRight];
[label1 release];
}
else
{
CGRect frame3=CGRectMake(0,0,80, 60);
MTLabel *label3=[[MTLabel alloc]init];
label3.frame=frame3;
label3.backgroundColor = [UIColor purpleColor];
label3.text=#"100";
label3.tag = 1003;
label3.autoresizingMask = UIViewAutoresizingFlexibleTopMargin &UIViewAutoresizingFlexibleWidth & UIViewAutoresizingFlexibleLeftMargin & UIViewAutoresizingFlexibleRightMargin;
label3.contentMode = UIViewContentModeTopLeft;
[label3 setTextAlignment:MTLabelTextAlignmentRight];
[cell.contentView addSubview:label3];
[label3 release];
}
}
FTS_book *book = [items objectAtIndex:indexPath.row];
if(indexPath.row==0)
{
MTLabel *label1 = (MTLabel*)[cell viewWithTag:1001];
label1.text= [NSString stringWithFormat:#"%d", book.chapter];
}
else
{
MTLabel *label3 = (MTLabel*)[cell viewWithTag:1003];
label3.text= [NSString stringWithFormat:#"%d", book.verse];
}
return cell;
}
Use different cell Id's for those two styles.
I want a UIPickerView to show up when I press a button (just like keyboard) and then go away when user taps anywhere on the screen. How can I do this? Thanks.
A bit more background: I have a UITextField called months in UITableViewCell. Now the best option for me is to put a UIPikcerView there and it will be easier for the user to just chose the month rather than having to type it out (and it's the better way). But UIPickerView looks really ugly in a UITableViewCell, not to mention I can't change it's gigantic size. So what should I do in this case?
This is how you should use UIPickerView for a textField in a UITableView.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];
textField.clearsOnBeginEditing = NO;
textField.textAlignment = UITextAlignmentRight;
textField.delegate = self;
[cell.contentView addSubview:textField];
//textField.returnKeyType = UIReturnKeyDone;
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
// if you want a UIPickerView for first row... then do the following //
// Here.. packSizePickerView is an object of UIPickerView
if (indexPath.row == 1)
{
textField.tag=0;
textField.delegate= self;
packSizePickerView.delegate = self;
packSizePickerView = [[UIPickerView alloc] init];
packSizePickerView.autoresizingMask=UIViewAutoresizingFlexibleWidth;
packSizePickerView.showsSelectionIndicator=YES;
textField.inputView = packSizePickerView;
}
// if you want to select date / months in row 2, go for UIDatePickerView //
if (indexPath.row == 1)
{
textField.tag = 1;
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
datePicker.tag = indexPath.row;
textField.delegate= self;
textField.inputView = datePicker;
[datePicker release];
}
}
// Configure the cell...
NSInteger row = [indexPath row];
cell.textLabel.text = [myArray objectAtIndex:row];
return cell;
}
And for datePickerValueChangedd
- (void)datePickerValueChangedd:(UIDatePicker*) datePicker{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 68, 68)];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
NSLog(#"I am inside the datePickerValueChanged - - %#", label.text);
[df release];
globalValue1 = label.text;
// use a global variable to copy the value from the pickerView. //
}
Now in the textFieldDidEndEditing:
-(void) textFieldDidEndEditing:(UITextField *)textField {
if (textField.tag ==0)
[textField setText: globalValue0];
if (textField.tag ==1)
[textField setText: globalValue1];
}
And to resign UIDatePicker, set the UIView as a UIControl and
resignFirstResponder
I think that you need to put your UIPickerView "outside" the viewable screen and animate it in when the button is pressed. I'm not really sure what the best way to get rid of it would be but you could probably listen for a tap on the parent view when the picker is visible and then animate it back out.