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.
Related
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
I want to disable reloading table view when scrolling. Now, my app when user scroll the uitableview, cellForRowAtIndexPath has been recalled. How can I disable it when srcolling? Please give me some advice. Thanks in advance.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"%d,%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *FileNameLabel;
UILabel *UploadTimeLabel;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CFileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 130, 30)];
UploadTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 20, 130, 25)];
FileNameLabel.tag = 1000;
FileNameLabel.backgroundColor = [UIColor clearColor];
FileNameLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
FileNameLabel.font = [UIFont boldSystemFontOfSize:14];
FileNameLabel.textColor = [UIColor blackColor];
// FileNameLabel.text =[temp objectAtIndex:indexPath.row];
[cell.contentView addSubview: FileNameLabel];
[FileNameLabel release];
UploadTimeLabel.tag = 2000;
UploadTimeLabel.backgroundColor = [UIColor clearColor];
UploadTimeLabel.font = [UIFont fontWithName:#"Helvetica" size:12];
UploadTimeLabel.textColor = [UIColor grayColor];
// UploadTimeLabel.text = [UploadTimeArray objectAtIndex:indexPath.row];
[cell.contentView addSubview: UploadTimeLabel];
[UploadTimeLabel release];
}
if( [OriginalArray count] > 0)
{
UILabel *fileNameLbl = (UILabel*)[cell.contentView viewWithTag:1000];
//fileNameLbl.text =[temp objectAtIndex:indexPath.row];
fileNameLbl.text =[[OriginalArray valueForKey:#"FILENAME"] objectAtIndex:indexPath.row];
UILabel *uploadlbl = (UILabel*)[cell.contentView viewWithTag:2000];
uploadlbl.text =[[OriginalArray valueForKey:#"UPLOADTIME"] objectAtIndex:indexPath.row];
}
_tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
return cell;
}
You cannot block the cellForRowAtIndexPath: from calling when scrolling the tableview. If something need not happen every time, You may keep it in if condition.
if (cell == nil)
{
//Functionality goes here when it not needed to happen every time.
}
Do not implement the method UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"yourID"]; or UITableViewCell *cell = [tableView dequeueCellWithReuseIdentifier:nil];
It will prevent the table view from reusing the cell. But its not a good idea if your tableview is going to contain large number of cell. Hope this helps. :)
Instead of trying to avoid being reloaded, maybe you could play with your data source, so that it appears as the data doesn't change. I hope you understand what I mean.
use dequecellforrowatindex method to avoid cell reloading.
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.
I added a UILabel when TableViewCell making. Code like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Special *special = [speciales objectAtIndex:indexPath.row];
......
UILabel *description = [[UILabel alloc] initWithFrame:CGRectMake(80, 21, 220, 50)];
description.text = special.specialDescription;
description.font = [UIFont fontWithName:#"Heiti SC" size:12];
description.textColor = [UIColor darkGrayColor];
description.lineBreakMode = UILineBreakModeWordWrap;
description.numberOfLines = 3;
[cell addSubview:description];
return cell;
}
It works well, but when I scrolled it from the bottom to top, and when I selected a row, the old value appeared at the same time. Who can help me fix this?
Thank you!
update : All of my codes is this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Special *special = [speciales objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 60, 60)];
img.image = special.specialIconImage;
[self addShadowToImage:img];
[cell addSubview:img];
UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(80, 5, 220, 16)];
name.text = special.specialName;
name.font = [UIFont fontWithName:#"Heiti SC" size:16];
[cell addSubview:name];
UILabel *description = [[UILabel alloc] initWithFrame:CGRectMake(80, 21, 220, 50)];
description.text = special.specialDescription;
description.font = [UIFont fontWithName:#"Heiti SC" size:12];
description.textColor = [UIColor darkGrayColor];
description.lineBreakMode = UILineBreakModeWordWrap;
description.numberOfLines = 3;
[cell addSubview:description];
return cell;
}
The problem is that you're adding the Image and Label subviews every time the cell is being called. Instead, you only want to add those subviews when you're creating the cell. Every time the cell gets called you just want to set the values of subviews. You'll want something like this (done off memory):
Special *special = [speciales objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 60, 60)];
[imageView setTag:100];
[cell addSubview:imageView];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 5, 220, 16)];
name.font = [UIFont fontWithName:#"Heiti SC" size:16];
[nameLabel setTag:101];
[cell addSubview:nameLabel];
UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 21, 220, 50)];
[descriptionLabel setTag:102];
descriptionLabel.font = [UIFont fontWithName:#"Heiti SC" size:12];
descriptionLabel.textColor = [UIColor darkGrayColor];
descriptionLabel.lineBreakMode = UILineBreakModeWordWrap;
descriptionLabel.numberOfLines = 3;
[cell addSubview:descriptionLabel];
}
UIImageView *img = (UIImageView *)[cell viewWithTag:100];
img.image = special.specialIconImage;
[self addShadowToImage:img];
UILabel *name = (UILabel *)[cell viewWithTag:101];
name.text = special.specialName;
UILabel *description = (UILabel *)[cell viewWithTag:102];
description.text = special.specialDescription;
return cell;
[tableView reloadData];
try this.
While I think you should be dequeueing cells to reuse them, it doesn't seem to be the root of your problem - unless you are reusing cells and didn't show us. There could be code there that points to the issue.
I think the issue could be related to redrawing. Try putting this at the end of your tableView:cellForRowAtIndex: method
[cell setNeedsDisplay];
This will force the UI to redraw the cell.
What does ..... mean in the code?
Are you using dequeueReusableCellWithIdentifier in there?
If That part of the code conaitns the code something like below, then It should work just fine-
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
Here are some things to keep in mind:
• The new views must be added when we instantiate a new cell, but not when we
reuse a cell (because a reused cell already has them).
• We must never send addSubview: to the cell itself — only to its contentView (or
some subview thereof).
• We should assign the new views an appropriate autoresizingMask, because the
cell’s content view might be resized.
• Each new view should be assigned a tag so that it can be referred to elsewhere.
Here is code:
//thanks to Thomas Hajcak's code
Special *special = [speciales objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 60, 60)];
[imageView setTag:100];
//autoresizingMask as follow
imageView.autoresizingMask = (UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleLeftMargin);
[cell.contentView addSubview:imageView];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 5, 220, 16)];
name.font = [UIFont fontWithName:#"Heiti SC" size:16];
[nameLabel setTag:101];
[cell.contentView addSubview:nameLabel];
UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 21, 220, 50)];
[descriptionLabel setTag:102];
descriptionLabel.font = [UIFont fontWithName:#"Heiti SC" size:12];
descriptionLabel.textColor = [UIColor darkGrayColor];
descriptionLabel.lineBreakMode = UILineBreakModeWordWrap;
descriptionLabel.numberOfLines = 3;
[cell.contentView addSubview:descriptionLabel];
}
UIImageView *img = (UIImageView *)[cell.contentView viewWithTag:100];
img.image = special.specialIconImage;
[self addShadowToImage:img];
UILabel *name = (UILabel *)[cell.contentView viewWithTag:101];
name.text = special.specialName;
UILabel *description = (UILabel *)[cell.contentView viewWithTag:102];
description.text = special.specialDescription;
return cell;
I have problem with the cell background color becoming clearcolor always. I set the uiview background color to gray color, tableview background color to clear color and I did not set tableviewcell background color to clear color. But the cell background always appears grey. Can any one have any idea about this.
Thanks
-(void)viewDidLoad
{
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"TableBackGround.png"]];
Acc_Details_TView.backgroundColor = [UIColor clearColor];
Acc_Details_TView.rowHeight = 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TransCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
switch ([Acc_Details_SegCtrl selectedSegmentIndex]) {
case 0:{
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"TableCell"] autorelease];
cell.backgroundColor =[UIColor clearColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
cell.detailTextLabel.text = [[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Date"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
}
NSString *titleName =[[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Title"] ;
if ([titleName length] > 19) {
cell.textLabel.text = [titleName substringWithRange:NSMakeRange(0, 20)];
}
else{
cell.textLabel.text = titleName;
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * acc_Amount = [[UILabel alloc] initWithFrame:CGRectMake(220, 5, 60,10)];
acc_Amount.textAlignment = UITextAlignmentRight;
acc_Amount.backgroundColor = [UIColor clearColor];
acc_Amount.text = [[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Amount"];
acc_Amount.font = [UIFont boldSystemFontOfSize:14];
[cell.contentView addSubview:acc_Amount];
UILabel * balance_Amount = [[UILabel alloc] initWithFrame:CGRectMake(220, 23, 60,10)];
balance_Amount.textAlignment = UITextAlignmentRight;
balance_Amount.text = #"$1234.50";
balance_Amount.backgroundColor = [UIColor clearColor];
balance_Amount.textColor = [UIColor grayColor];
balance_Amount.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:balance_Amount];
return cell;
}
}
}
Try setting your cell's background colour in the method
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
rather than in your cellForRowAtIndexPath: method.
Your cells are not exactly transparent. Setting UITableView's backgroundColor does some crazy undocumented stuff. Best way to see this is to set it to some semi-transparent color like [UIColor colorWithWhite:0.5 alpha:0.5] by which you get something like this:
To fix your problem, you will have to set cells' contentView.backgroundColor and backgroundColors of all the subviews after setting tableView's. Here is your cellForRowAtIndexPath: updated with this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TransCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIColor *cellBackgroundColor = [UIColor whiteColor];
switch ([Acc_Details_SegCtrl selectedSegmentIndex]) {
case 0:{
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"TableCell"] autorelease];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
cell.detailTextLabel.text = [[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Date"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
cell.accessoryView.backgroundColor = cellBackgroundColor;
cell.backgroundView.backgroundColor = cellBackgroundColor;
cell.contentView.backgroundColor = cellBackgroundColor;
cell.textLabel.backgroundColor = cellBackgroundColor;
cell.detailTextLabel.backgroundColor = cellBackgroundColor;
UIView *backView = [[UIView alloc] initWithFrame:cell.frame];
backView.backgroundColor = cellBackgroundColor;
cell.backgroundView = backView;
[backView release];
}
NSString *titleName =[[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Title"] ;
if ([titleName length] > 19) {
cell.textLabel.text = [titleName substringWithRange:NSMakeRange(0, 20)];
}
else{
cell.textLabel.text = titleName;
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * acc_Amount = [[UILabel alloc] initWithFrame:CGRectMake(220, 5, 60,10)];
acc_Amount.textAlignment = UITextAlignmentRight;
acc_Amount.backgroundColor = cellBackgroundColor;
acc_Amount.text = [[transcationsList objectAtIndex:([indexPath row])] valueForKey:#"Amount"];
acc_Amount.font = [UIFont boldSystemFontOfSize:14];
[cell.contentView addSubview:acc_Amount];
UILabel * balance_Amount = [[UILabel alloc] initWithFrame:CGRectMake(220, 23, 60,10)];
balance_Amount.textAlignment = UITextAlignmentRight;
balance_Amount.text = #"$1234.50";
balance_Amount.backgroundColor = cellBackgroundColor];
balance_Amount.textColor = [UIColor grayColor];
balance_Amount.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:balance_Amount];
}
}
return cell;
}
I didn't understand your question. You set the table's background to grey, then clear, but you didn't set it as clear, and then it appears grey, which you didn't want even though you set it as grey?
table.backgroundColor = [UIColor clearColor];