ios - adding text fields to uitableviewcell programmatically not working - ios

Rookie ios question. I am trying to create a sign up form using a table view controller. I am trying add textfields to each cell programmatically in the cellForRowAtIndexPath method but all my text fields seem to getting created on the first cell - one overlapping the other. Here is my code.
Here is how my cells are rendering. I think I am doing something goofy with the part that is reusing the cells. I did check some some other similar threads on stackoverflow but none of them helped. Could you please tell me what i am missing or is this even the way this is supposed to be done. Your inputs are really appreciated.
Thanks,
Mike
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"signUpFields" forIndexPath:indexPath];
// Configure the cell...
if (indexPath.row == 0){
//self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.firstName.placeholder = #"First Name";
self.firstName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.firstName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.firstName;
[cell.contentView addSubview:self.firstName];
}
if (indexPath.row == 1){
self.lastName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.lastName.placeholder = #"Last Name";
self.lastName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.lastName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.lastName;
[cell.contentView addSubview:self.lastName];
}
if (indexPath.row == 2){
self.emailId = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.emailId.placeholder = #"Email Id";
self.emailId.autocorrectionType = UITextAutocorrectionTypeNo;
[self.emailId setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.emailId;
[cell.contentView addSubview:self.emailId];
}
if (indexPath.row == 3){
self.password = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.password.placeholder = #"Password";
self.password.secureTextEntry = YES;
self.password.autocorrectionType = UITextAutocorrectionTypeNo;
[self.password setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.password;
[cell.contentView addSubview:self.password];
}
self.firstName.delegate = self;
self.lastName.delegate = self;
self.emailId.delegate = self;
self.password.delegate = self;
[self.signUpTable addSubview:self.firstName];
[self.signUpTable addSubview:self.lastName];
[self.signUpTable addSubview:self.emailId];
[self.signUpTable addSubview:self.password];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}

Try this..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.row == 0){
//self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.firstName.placeholder = #"First Name";
self.firstName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.firstName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.firstName;
[cell addSubview:self.firstName];
}
if (indexPath.row == 1){
self.lastName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.lastName.placeholder = #"Last Name";
self.lastName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.lastName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.lastName;
[cell addSubview:self.lastName];
}
if (indexPath.row == 2){
self.emailId = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.emailId.placeholder = #"Email Id";
self.emailId.autocorrectionType = UITextAutocorrectionTypeNo;
[self.emailId setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.emailId;
[cell addSubview:self.emailId];
}
if (indexPath.row == 3){
self.password = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.password.placeholder = #"Password";
self.password.secureTextEntry = YES;
self.password.autocorrectionType = UITextAutocorrectionTypeNo;
[self.password setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.password;
[cell addSubview:self.password];
}
self.firstName.delegate = self;
self.lastName.delegate = self;
self.emailId.delegate = self;
self.password.delegate = self;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
no need to add again text view in table view, this is wrong. Try this, this will work for you but better you should create a custom Cell and use. That is the best way to do it, because you can use whatever you want with Cell.

Don't add them as subviews, set them as the cell's accessory view.
- (UITextField*)getTextField{
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 20, 35)];
tf.delegate = self;
tf.textColor = [UIColor colorWithRed:.231 green:.337 blue:.533 alpha:1];
tf.autocorrectionType = UITextAutocorrectionTypeNo;
tf.borderStyle = UITextBorderStyleNone;
tf.frame = CGRectMake(0, 20, 170, 30);
tf.clearButtonMode = UITextFieldViewModeWhileEditing;
tf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
tf.font = [UIFont systemFontOfSize:13];
return tf;
}
- (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];
cell.textLabel.font = [UIFont systemFontOfSize:13];
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
cell.detailTextLabel.numberOfLines = 2;
}
if (indexPath.section == 0) {
UITextField *tf = (UITextField*)cell.accessoryView;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.numberOfLines = 2;
tf = [self getTextField];
cell.accessoryView = cell.editingAccessoryView = tf;
[((UITextField*)cell.accessoryView) setBorderStyle:self.tableView.editing ? UITextBorderStyleRoundedRect : UITextBorderStyleNone];
[((UITextField*)cell.accessoryView) setUserInteractionEnabled:self.tableView.editing ? YES : NO];
[((UITextField*)cell.accessoryView) setTextAlignment:!self.tableView.editing ? UITextAlignmentRight : UITextAlignmentLeft];
((UITextField*)cell.accessoryView).tag = indexPath.row;
}
return cell;
}
The idea is that the cell is re-drawn each time it appears on screen, coming from off the screen and if you add the text field with addSubview:, it will add it each time as well. You COULD do it, but then you have to clear the cell's contentView of subviews, but that requires extra work, cpu and memory use, and not to say it's the least elegant solution.

Looks like you have just four cells you want to display. This is a static case, the cells don't change, you should create this tableView and its cells statically in the xib/storyboard. That is the preferred way here.
If you really want to do it programmatically, create four UITableViewCells with the behavior you want before hand. Keep them in an array. Inside cellForRowAtIndex path return cellArray[indexPath.row];
Note this is the best approach only because you have just four tableViewCells.
ReuseIdentifiers come in handy only if you have more cells than can be accommodated on the screen at once. So in your case, you never actually reuse the cells.

keep this one and try it,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *MyIdentifier = [NSString stringWithFormat:#"%d%d",indexPath.row,indexPath.section];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
//your stuff.
}
}

Try to use this one ...And there is no need to add these textfield to tableview. So please remove some code..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"signUpFields" forIndexPath:indexPath];
// Configure the cell...
if (indexPath.row == 0){
//self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, 280, 21)];
self.firstName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.firstName.placeholder = #"First Name";
self.firstName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.firstName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.firstName;
[cell addSubview:self.firstName];
}
if (indexPath.row == 1){
self.lastName = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.lastName.placeholder = #"Last Name";
self.lastName.autocorrectionType = UITextAutocorrectionTypeNo;
[self.lastName setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.lastName;
[cell addSubview:self.lastName];
}
if (indexPath.row == 2){
self.emailId = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.emailId.placeholder = #"Email Id";
self.emailId.autocorrectionType = UITextAutocorrectionTypeNo;
[self.emailId setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.emailId;
[cell addSubview:self.emailId];
}
if (indexPath.row == 3){
self.password = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.password.placeholder = #"Password";
self.password.secureTextEntry = YES;
self.password.autocorrectionType = UITextAutocorrectionTypeNo;
[self.password setClearButtonMode:UITextFieldViewModeWhileEditing];
//cell.accessoryView = self.password;
[cell addSubview:self.password];
}
self.firstName.delegate = self;
self.lastName.delegate = self;
self.emailId.delegate = self;
self.password.delegate = self;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}

Instead of writing more cells just create one custom cell with textfield.Give the tag for each textfield and also set the count of rows in numberOfRowsIntheSections then it will display the cells how much you need. I think it will helps you.

Before You follow my Answer i wnat to tell you that following code is bad for memory management because it will create new cell for each rows of UITableView, so be careful for it.
But it is better to use, When UITableView Have Limited rows (about 50-100 may be ) then following code is helpful in your case, use it, If it is suitable for you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
/// Put/Create your UITextField or any Controls here
}
return cell;
}

#Mike : First of all I will suggest you to go with StoryBoard or Nib files.
If you use this, then you can use following code
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UITextField *txtField = (UITextField *)[cell viewWithTag:1];
txtField.text = #"Latest";
return cell;
}
Based on row number you can set text.
If you want to add the UITextField at run time. then you can use following code.
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(165.0, 7.0, 150.0, 30.0)];
txtField.text = #"Latest";
[cell.contentView addSubview:txtField];
return cell;
}
You can assign different tag and based on tags you can store those values.

Related

No access to UILabel

I am setting an UILabel inside of the cellForRowAtIndexPath method and when the user changes the text, the label should change. But even it is not nil, it doesn't change.
#property UILabel *myLabel;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, textView.frame.size.width, 37)];
self.myLabel.text = #"Old Text";
}
- (void)textViewDidChange:(UITextView *)textView {
self.myLabel.textColor = [UIColor redColor];
self.myLabel.text = #"New Text";
}
I found a solution where some people are changing the UILabel in the main thread but that's not working for me.
dispatch_async(dispatch_get_main_queue(), ^{
// Do in main thread
});
If you want to modify the label of a cell that's on-screen "on the fly" then you need a way to reach the label.
What I usually do is to create a template for the cell in IB, define a custom subclass of UITableViewCell, and set the cell's class to that custom subclass. Then I connect outlets between the cell and all the custom fields I've created.
In my cellForRowAtIndexPath method, I dequeue a cell and cast it to my custom type. Then I reference the fields in the cell through the cell, e.g.
cell.myLabel.
If you add a new field to your cell in cellForRowAtIndexPath you have a couple of problems. First, you need to make sure you don't add another copy of that new field when you recycle the cell. Second, you need a way to get to the field if you want to modify it, as in your question. There are ways to deal with these problems, but the approach I outlined above is cleaner.
Duncan, I'm sorry, here is the rest of the cellForRowAtIndexPath. I thought it could not be a problem of reusing the cell as I'm not scrolling so the cell should not be recreated.
#property NSString *textField_1;
#property NSString *textField_2;
// ...
#property UILabel *myLabel;
#end
#implementation TableViewController
- (void)textViewDidChange:(UITextView *)textView
{
self.myLabel.textColor = [UIColor redColor];
self.myLabel.text = #"New Text";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if(indexPath.section == 0)
{
float displayResolutionWidth = self.view.frame.size.width;
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, displayResolutionWidth - 165, 50)];
textField.delegate = self;
textField.tag = indexPath.row;
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, displayResolutionWidth - 90, 176)];
textView.delegate = self;
textView.tag = indexPath.row;
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, textView.frame.size.width, 37)];
self.myLabel.textColor = [UIColor redColor];
if(indexPath.row == 17)
{
cell.accessoryView = textView;
[textView addSubview:self.myLabel];
}
else if (indexPath.row != 17)
{
cell.accessoryView = textField;
}
if (self.object)
{
if (indexPath.row == 0)
textField.text = self.object.property_1;
if (indexPath.row == 1)
textField.text = self.object.property_2;
}
else if (!self.object)
{
if (indexPath.row == 0)
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(#"Placeholder_1", #"")
attributes:#{NSForegroundColorAttributeName: [UIColor greenColor]}];
if (indexPath.row == 1)
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(#"Placeholder_2", #"")
attributes:#{NSForegroundColorAttributeName: [UIColor greenColor]}];
if (indexPath.row == 17)
self.myLabel.text = "Old Text";
}
if (indexPath.row != 17)
{
cell.textLabel.text = [self.arrayWithObjectData objectAtIndex:indexPath.row];
}
else if (indexPath.row == 17)
{
UILabel *mylabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 150, 40)];
mylabel.text = self.arrayWithObjectData[17];
mylabel.textColor = [UIColor COLOR_TEXT];
[cell.contentView addSubview:mylabel];
}
}
return cell;
}
#end

Adding textfield dynamically to table view cell and scroll it horizontally

I have created an table view shown in landscape orientation.
I want to add multiple text fields dynamically to table cell and also want to get data can any one suggest me. How can I scroll it horizontally in iOS?
UITextField *mytextField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];
mytextField.clearsOnBeginEditing = NO;
mytextField.textAlignment = UITextAlignmentRight;
mytextField.delegate = self;
[yourCell.contentView addSubview: mytextField];
or
try like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.row == 0){
21)];
self.mytextField1 = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.mytextField1.placeholder = #"mytextField1";
self.mytextField1.autocorrectionType = UITextAutocorrectionTypeNo;
[self.mytextField1 setClearButtonMode:UITextFieldViewModeWhileEditing];
[cell addSubview:self.mytextField1];
}
if (indexPath.row == 1){
self.mytextField2 = [[UITextField alloc] initWithFrame:CGRectMake(120, 13, 375, 30)];
self.mytextField2.placeholder = #"mytextField2";
self.mytextField2.autocorrectionType = UITextAutocorrectionTypeNo;
[self.mytextField2 setClearButtonMode:UITextFieldViewModeWhileEditing];
[cell addSubview:self.mytextField2];
}
if (indexPath.row == 2){
// add here
}
if (indexPath.row == 3){
}
self.mytextField1.delegate = self;
self.mytextField2.delegate = self;
// and other also here
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Instead of adding textField directly into tableCell you can first add a scroll view on tableCell than add multiple textField on this scroll view. Set the content size accordingly of scroll view, so that it will scroll easily to the end.

UITextViews not cleared when selected in a UITableView

I'm implementing a UITableView with text-views as the content view of my cells.
The data that the user enters is saved in a settings dictionary when the user hits the return key:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == _textFieldOne){
[settingsDictionary setObject: _textFieldOne.text forKey:#"EntryOneText"];
[settingsDictionary stringValueForKey:#"textFieldOneValue"];
[self postNotificationSettingsUpdate:settingsDictionary];
didTestPostNotificationSettings = YES;
}
These saved values should be displayed in the text-field when the user returns back to the screen, which I've done using the code below:
//Set the value in the text fields from the settings dictionary
NSString *textFieldOneText = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMin"];
_textFieldOne.text = textFieldOneValue;
So far, everything seems to work as expected: text input is saved, and shown in the text-field when the user returns to screen. However, if the row of the TableView that holds the text-field is select (not the text-field itself), the text-field displays the behavior shown below:
It appears as if the text-field is showing both the newly inputted entry, as well as the entry that was last saved.
EDIT I'ved added more of my cellForRowAtIndexPath method below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubscribedRedZoneAlertRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"RedZoneAlertCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
UISwitch *cellSwitch = nil;
NSNumber *position = enabledRedZoneAlertRows[indexPath.row];
switch (position.integerValue) {
case CarPerManHourRow: {
cell.textLabel.text = NSLocalizedString(#"Label", #"Label Row");
cellSwitch = [[UISwitch alloc] init];
cellSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:SwitchKey];
cellSwitch.tag = SwitchTag;
[cellSwitch addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = cellSwitch;
if ([[self.settingsDictionary valueForKey:#"RedZoneCarsPerManHrOnOff"]isEqual: #"1"]){
[cellSwitch setOn:YES];
}
break;
}
case TextFieldRow: {
static NSString *CellIdentifier = #"ConfigCell";
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
[cell.contentView addSubview:_textFieldOne];
[cell.contentView addSubview:_textFieldTwo];
[cell.contentView addSubview:_spacingLabel];
}
cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
_textFieldOne = [[UITextField alloc]initWithFrame:CGRectMake(25, 0, 50, 30)];
_textFieldTwo = [[UITextField alloc]initWithFrame:CGRectMake(100, 0, 50, 30)];
_textFieldOne.delegate = self;
_textFieldTwo.delegate = self;
_textFieldOne.placeholder = #"Auto";
_textFieldTwo.placeholder = #"Auto";
[_textFieldOne setTextAlignment:NSTextAlignmentCenter];
[_textFieldTwo setTextAlignment:NSTextAlignmentCenter];
//Set the value in the text fields from the settings dictionary
NSString *textFieldOneText = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMin"];
NSString *textFieldTwoText = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMax"];
NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMax"];
NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMax"];
_textFieldOne.text = textFieldOneValue;
_textFieldTwo.text = textFieldTwoValue
_textFieldOne.backgroundColor = [UIColor whiteColor];
_textFieldTwo.backgroundColor = [UIColor whiteColor];
_textFieldOne.tintColor = [UIColor blackColor];
_textFieldTwo.tintColor = [UIColor blackColor];
[_textFieldOne.layer setCornerRadius:7.0f];
[_textFieldTwo.layer setCornerRadius:7.0f];
[_textFieldOne setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[_textFieldTwo setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
_textFieldOne.returnKeyType = UIReturnKeyNext;
_textFieldTwo.returnKeyType = UIReturnKeyDone;
_spacingLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 35, 30)];
_spacingLabel.text = #"–";
_spacingLabel.textColor = [UIColor colorWithRed:0.658 green:0.658 blue:0.658 alpha:1];
[_spacingLabel setTextAlignment:NSTextAlignmentCenter];
_spacingLabel.backgroundColor = [UIColor clearColor];
//[cell.contentView addSubview:_textFieldOne];
//[cell.contentView addSubview:_textFieldTwo];
//[cell.contentView addSubview:_spacingLabel];
break;
}
return cell;
}
EDIT TWO
Below is my attempt at fixing my issue based on jherran's answer. However, I am still experiencing the same problem.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubscribedRedZoneAlertRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"RedZoneAlertCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
UISwitch *cellSwitch = nil;
NSNumber *position = enabledRedZoneAlertRows[indexPath.row];
switch (position.integerValue) {
case CarPerManHourRow: {
cell.textLabel.text = NSLocalizedString(#"Label", #"Label Row");
cellSwitch = [[UISwitch alloc] init];
cellSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:SWSettingCarsPerManHour];
cellSwitch.tag = SaveCarsPerManHourTag;
[cellSwitch addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = cellSwitch;
if ([[self.settingsDictionary valueForKey:#"RedZoneCarsPerManHrOnOff"]isEqual: #"1"]){
[cellSwitch setOn:YES];
}
break;
}
case CarsPerManHourConfigRow: {
static NSString *CellIdentifier = #"ConfigCell";
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
_carsPerManHourMinTextField = [[UITextField alloc]initWithFrame:CGRectMake(25, 0, 50, 30)];
_carsPerManHourMaxTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 0, 50, 30)];
_textFieldOne.delegate = self;
_textFieldTwo.delegate = self;
_textFieldOne.placeholder = #"Auto";
_textFieldTwo.placeholder = #"Auto";
[_textFieldOne setTextAlignment:NSTextAlignmentCenter];
[_textFieldTwo setTextAlignment:NSTextAlignmentCenter];
_textFieldOne.backgroundColor = [UIColor whiteColor];
_textFieldTwo.backgroundColor = [UIColor whiteColor];
_textFieldOne.tintColor = [UIColor blackColor];
_textFieldTwo.tintColor = [UIColor blackColor];
[_textFieldOne.layer setCornerRadius:7.0f];
[_textFieldTwo.layer setCornerRadius:7.0f];
[_textFieldOne setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[_carsPerManHourMaxTextField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
_textFieldOne.returnKeyType = UIReturnKeyNext;
_textFieldTwo.returnKeyType = UIReturnKeyDone;
_spacingLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 35, 30)];
_spacingLabel.text = #"–";
_spacingLabel.textColor = [UIColor colorWithRed:0.658 green:0.658 blue:0.658 alpha:1];
[_spacingLabel setTextAlignment:NSTextAlignmentCenter];
_spacingLabel.backgroundColor = [UIColor clearColor];
NSLog(#"%#", _textFieldOne.text);
NSLog(#"%#",_carsPerManHourMaxTextField.text);
[cell.contentView addSubview: _textFieldOne];
[cell.contentView addSubview: _textFieldTwo];
[cell.contentView addSubview:_spacingLabel];
cell.tag = 1;
}
else {
_textFieldOne = (UITextField *)[cell.contentView viewWithTag:1];
_textFieldTwo = (UITextField *)[cell.contentView viewWithTag:1];
_spacingLabel = (UILabel *)[cell.contentView viewWithTag:1];
}
NSString * _textFieldOne = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMin"];
NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:#"RedZoneCarsPerManHrMax"];
_textFieldOne.text = carsPerManHrMin;
_textFieldTwo.text = carsPerManHrMax;
How do I modify my code so that this behavior does not occur?
Check your cellForRowAtIndexPath, as cells are reused, you are probably not loading the cell property.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*
* This is an important bit, it asks the table view if it has any available cells
* already created which it is not using (if they are offscreen), so that it can
* reuse them (saving the time of alloc/init/load from xib a new cell ).
* The identifier is there to differentiate between different types of cells
* (you can display different types of cells in the same table view)
*/
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
/*
* If the cell is nil it means no cell was available for reuse and that we should
* create a new one.
*/
UILabel *label;
if (cell == nil) {
/*
* Actually create a new cell (with an identifier so that it can be dequeued).
*/
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
cell.tag = 1;
[cell.contentView addSubview:label];
} else {
label = (UILabel *)[cell.contentView viewWithTag:1];
}
/*
* Now that we have a cell we can configure it to display the data corresponding to
* this row/section
*/
label.text = #"whatever";
}
EDIT: When your cell exits and it's reused, you are adding a view ([cell.contentView addSubview:_textFieldOne]) each time the cell is reused.
Ok, it is as I suspected. Every time the cell is taken out out the reuse queue, you create a new instance of textfield and add it to the content view. So basically the content view is piling up with new textfields.
What you should do is
1) to have a custom cell and make the cell the sole class responsible for its internals
2) expose only a configuration method to pass a raw text to cell
3) call that configuration method when thr cell is reused.
4) keep a reference to the textfield inside the custom cell to be able to update the text value any time incl. when it is recycled in cellforrowatindexpath

UITableView dequeue not working as expected

As I scroll down the list, all the rows are there, but they keep adding more subviews the more they appear on the visible frame
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuse = #"RuleCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuse];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:reuse];
}
NSUInteger row = indexPath.row;
[self createCell: cell onRow: row];
return cell;
}
- (void) createCell: (UITableViewCell*)cell onRow: (NSUInteger)row
{
UIImageView* bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"cell_background_spade_active.png"]];
cell.backgroundView = bgImage;
cell.textLabel.hidden = YES;
UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(100, CGRectGetHeight(cell.frame) / 2, 200, 50)];
titleLabel.text = [[self.ruleList objectAtIndex: row] objectForKey: TitleKey];
titleLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview: titleLabel];
}
I think you need to execute almost all of the logic that's in createCell: only within the if (cell == nil){ segment of your code. The part that should execute where you're currently calling createCell: is just getting a reference to the titleLabel and setting its text value.
To clarify, here's the kind of modification I'm suggesting (not tested, but should give the right idea):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuse = #"RuleCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuse];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:reuse];
[self setUpCell: cell];
}
NSUInteger row = indexPath.row;
UILabel *titleLabel = (UILabel *)[cell.contentView viewWithTag:42];
titleLabel.text = [[self.ruleList objectAtIndex: row] objectForKey: TitleKey];
return cell;
}
- (void) setUpCell: (UITableViewCell*)cell
{
UIImageView* bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"cell_background_spade_active.png"]];
cell.backgroundView = bgImage;
cell.textLabel.hidden = YES;
UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(100, CGRectGetHeight(cell.frame) / 2, 200, 50)];
titleLabel.tag = 42;
titleLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview: titleLabel];
}

UItableView multiplle data printed

I am creating grouped table in my application.
It works fine. But when I scroll the table upward and backward reprinted text on previous cell. It look like horrible.
This is my Code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellID"];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"cellID"] autorelease];
}
/*
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
*/
if(indexPath.section == 0)
{
cell.backgroundColor = [UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
float rowHeight = [DetailViewController calculateHeightOfTextFromWidth:[dict objectForKey:#"golf_name"] :[UIFont boldSystemFontOfSize:18] :290 :UILineBreakModeTailTruncation];
UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 290, rowHeight)];
categorName.font = [UIFont boldSystemFontOfSize:20];
categorName.numberOfLines = 5;
categorName.backgroundColor = [UIColor clearColor];
categorName.textColor = [UIColor whiteColor];
categorName.text = [dict objectForKey:#"golf_name"];
[cell addSubview:categorName];
[categorName release];
}
if(indexPath.section == 1)
{
cell.backgroundColor = [UIColor whiteColor];
cell.accessoryType = UITableViewCellAccessoryNone;
UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 70, 20)];
categorName.font = [UIFont boldSystemFontOfSize:15];
categorName.numberOfLines = 5;
categorName.backgroundColor = [UIColor clearColor];
categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
categorName.text = #"Phone";
[cell addSubview:categorName];
[categorName release];
UILabel *phone = [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 290, 20)];
phone.font = [UIFont boldSystemFontOfSize:15];
phone.numberOfLines = 5;
phone.backgroundColor = [UIColor clearColor];
//categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
phone.text = [dict objectForKey:#"golf_phone"];
[cell addSubview:phone];
[phone release];
}
if(indexPath.section == 2)
{
cell.backgroundColor = [UIColor whiteColor];
cell.accessoryType = UITableViewCellAccessoryNone;
UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 90, 20)];
categorName.font = [UIFont boldSystemFontOfSize:15];
categorName.numberOfLines = 5;
categorName.backgroundColor = [UIColor clearColor];
categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
categorName.text = #"Home page";
[cell addSubview:categorName];
[categorName release];
UILabel *phone = [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 230, 20)];
phone.font = [UIFont boldSystemFontOfSize:15];
phone.numberOfLines = 5;
phone.backgroundColor = [UIColor clearColor];
//categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
phone.text = [dict objectForKey:#"golf_url"];
[cell addSubview:phone];
[phone release];
}
.......
.....
return cell;
}
Update
My original answer was not the correct way to reuse UITableViewCell's. You should never use "CellID%d%d"(indexPath.row & indexPath.column) as cell identifier, that defeats the very purpose of cell reuse. It will create separate UITableViewCell for every row in the table, and every one of those cells stays in memory. Imagine what will happen if you have a tableView with around 1000 rows.
The real answer to OP's question is - make sure to reset a UITableViewCell returned by dequeueReusableCellWithIdentifier because it might return a cell that is already used and its UI populated. For example, if you didn't reset the texts in UILabel, it might contain strings that should have been shown in a different row of your tableView.
My original Answer (Don't use this)
Hiren, just try,
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"CellID%d%d",indexPath.section,indexPath.row]];
if (!cell){
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:#"CellID%d%d",indexPath.section,indexPath.row]] autorelease];
}
instead of
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellID"];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"cellID"] autorelease];
}
Please read this..you will understand how to give cell identifiers..
When you create the UITableView object, Set the rowHeight for each cell.
myTableView.rowHeight = 50; //Depend on your requirement,
Let me know if you still struggle to get the desire result.
If your cell's height is not constant then implement heightForRowAtIndexPath method,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
And return different-2 height for each cell.
try adding any color because clearcolor is making label transparent.

Resources