Selecting a cell shows a button and deselecting hides the button - ios

I want a button to show when i select a cell, when i select the same cell or another cell i want the button to hide. So one button should only be visible at a time.
What i have:
in my .h file:
#property (strong, nonatomic) NSIndexPath *isselectednow;
and my .m file:
Viewdidload:
self.isselectednow = [NSIndexPath indexPathForRow:7 inSection:1];
cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//[cell addSubview:[self drawSeparationView:(indexPath.row)]];
UILabel *DateName = (UILabel *)[cell viewWithTag:100100];
DateName.textColor = [UIColor blackColor];
//DateName.text = [NSString stringWithFormat:#"%ld",(long)indexPath.row ];
DateName.text = objects[indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(buttonOnCellPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Update" forState:UIControlStateNormal];
button.frame = CGRectMake(DEVICE_SIZE.width - 60, 18, 55, 15);
[cell addSubview:button];
if ([indexPath compare:self.isselectednow] == NSOrderedSame) {
button.hidden = NO;
}
else{
button.hidden = YES;
}
UILabel *lbl1 = (UILabel *)[cell viewWithTag:100101];
lbl1.textColor = UIColorFromRGB(0x141414);
UILabel *lbl2 = (UILabel *)[cell viewWithTag:100102];
lbl2.textColor = UIColorFromRGB(0x141414);
UILabel *lbl3 = (UILabel *)[cell viewWithTag:100103];
lbl3.textColor = UIColorFromRGB(0x141414);
UILabel *lbl4 = (UILabel *)[cell viewWithTag:100104];
lbl4.textColor = UIColorFromRGB(0x141414);
UILabel *lbl5 = (UILabel *)[cell viewWithTag:100105];
lbl5.textColor = UIColorFromRGB(0x141414);
UITextField *breakfastName = (UITextField *) [cell viewWithTag:100200];
breakfastName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
breakfastName.textColor = UIColorFromRGB(0x141414);
[breakfastName setDelegate:self];
//[breakfastName addTarget:self action:#selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
UITextField *OutName = (UITextField *) [cell viewWithTag:100201];
OutName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
OutName.textColor = UIColorFromRGB(0x141414);
[OutName setDelegate:self];
UITextField *lunchName = (UITextField *) [cell viewWithTag:100202];
lunchName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
lunchName.textColor = UIColorFromRGB(0x141414);
[lunchName setDelegate:self];
UITextField *InName = (UITextField *) [cell viewWithTag:100203];
InName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
InName.textColor = UIColorFromRGB(0x141414);
[InName setDelegate:self];
UITextField *eveningName = (UITextField *) [cell viewWithTag:100204];
eveningName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
eveningName.textColor = UIColorFromRGB(0x141414);
[eveningName setDelegate:self];
UITextField *othersName = (UITextField *) [cell viewWithTag:100205];
othersName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
othersName.textColor = UIColorFromRGB(0x141414);
cell.clipsToBounds = YES;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor = UIColorFromRGB(0xf3f0e9);
return cell;
}
didSelectRowAtIndexPath:
[tableView beginUpdates];
if ([indexPath compare:self.isselectednow] == NSOrderedSame) {
self.isselectednow = nil;
}
else{
self.isselectednow = indexPath;
}
[tableView endUpdates];
//[tableView reloadData];

From the docs about beginUpdates:
Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: and indexPathsForVisibleRows) to be animated simultaneously.
Although you've changed the isSelectedNow boolean, you haven't actually specified any insertion, deletion, or selection operations between beginUpdates and endUpdates. So you're not actually beginning or ending any updates to the cells' content with that code.
I'm not sure what you're trying to do, but taking out [tableView beginUpdates]; and [tableView beginUpdates]; and reinserting [tableView reloadData]; would result in a proper data reload.
Edit:
Aside from that, the problem is that you're reusing your cells with dequeueReusableCellWithIdentifier:, but you're adding a new UIButton subview each time, so you're basically putting each new UIButton over the old. I suggest doing what you've done for all your labels and textfields in cellForRowAtIndexPath: -- reuse your update button by adding it to your custom table view cell and accessing it with viewWithTag:.

Related

UISwitch off state is not stable while scrolling in tableview

I'm creating a UISwitch programmatically in one of the tableview datasource function(cell for row at index). when I'm scrolling the table view, the OFF state switches are malfunctioned(UI) two rounds appeared. Attaching the screenshot of the switch.
Appreciate your help!
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:#"name"];
description.text = [displayDict objectForKey:#"description"];
UISwitch *myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60, (cell.contentView.frame.size.height/2)-20 , 100, 100)];
myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
[cell.contentView addSubview:myswitch];
myswitch.tag = indexPath.row;
[myswitch addTarget:self action:#selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
if ([[displayDict objectForKey:#"status"] isEqualToString:#"ACTIVE"]) {
[myswitch setOn:YES animated:YES];
}
else
{
[myswitch setOn:NO animated:YES];
}
return cell;
}
I have faced the same issue and fixed with following code before creating switch
for(UIView *subView in cell. contentView.subviews){
if ([subView isKindOfClass:[UISwitch class]]) {
[subView removeFromSuperview];
}
}
Or
static NSString *TableIdentifier = #"YourCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
//place your all UI elements code here.
}
I have updated your code, try this will work for you,
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:#"name"];
description.text = [displayDict objectForKey:#"description"];
UISwitch *myswitch = [cell.contentView viewWithTag:indexPath.row+597];
if(mySwitch == nil){
myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60,(cell.contentView.frame.size.height/2)-20 , 100, 100)];
[cell.contentView addSubview:myswitch];
[myswitch addTarget:self action:#selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
}
myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
myswitch.tag = indexPath.row+597; //597 is extra number added to tag
if ([[displayDict objectForKey:#"status"] isEqualToString:#"ACTIVE"]) {
[myswitch setOn:YES animated:YES];
}
else
{
[myswitch setOn:NO animated:YES];
}
return cell;
}

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

ImageView with Reusable Cell

I have to create custom UITableView and generally cell has UIImageView, and two UILabel when image of UIImageView is depend upon content which i got from server. so some cell has image and some has no image.
Problem is that when i use reusability of cell then previous UIImageView's image remain as it.. how can i remove it and implement my content on cell proper way.
Following is mine code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *isImgOfTable = [[self.listOfEvents objectAtIndex:indexPath.row] objectForKey:#"EventImage"];
NSString *CellIdentifier = #"Cell";
//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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if([isImgOfTable length] > 0)
{
UIImageView *imgOfEvent = [[UIImageView alloc] init];
imgOfEvent.tag = 101;
[cell.contentView addSubview: imgOfEvent];
}
UILabel *lblEventTitle = [[UILabel alloc] init];
lblEventTitle.tag = 102;
[cell.contentView addSubview:lblEventTitle];
UILabel *lblDescription = [[UILabel alloc] init];
lblDescription.tag = 103;
[cell.contentView addSubview:lblDescription];
}
if([isImgOfTable length] > 0)
{
NSString *newPath = #"";
UIImageView *imgEvent = (UIImageView *) [cell.contentView viewWithTag:101];
imgEvent.userInteractionEnabled = YES;
newPath = [[GeneralClass getDocumentDirectory] stringByAppendingPathComponent:[[self.listOfEvents objectAtIndex:indexPath.row] objectForKey:#"EventImage"]];
imgEvent.frame = CGRectMake(mainX, 4, 45, 45);
imgEvent.backgroundColor = [UIColor colorWithRed:(187/255.f) green:(226/255.f) blue:(255/255.f) alpha:1.0f];
imgEvent.layer.cornerRadius = 7;
imgEvent.layer.borderColor = [UIColor colorWithRed:(224/255.f) green:(224/255.f) blue:(224/255.f) alpha:1.0f].CGColor;
imgEvent.layer.borderWidth = 1;
imgEvent.clipsToBounds = YES;
imgEvent.image = [UIImage imageWithContentsOfFile:newPath];
}
UILabel *lblEventTitle = (UILabel*) [cell.contentView viewWithTag:102];
.
.
// Code of UILabel *lblEventTitle
UILabel *lblEventDescription = (UILabel*) [cell.contentView viewWithTag:103];
.
.
// Code of UILabel *lblEventDescription
return cell;
}
NOTE: I must want to use reusability of cell. I dont want to fix such like
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d", indexPath.section, indexPath.row];
And also i am not used UITableViewCell class so may be it is not possible to call/override prepareForReuse
Please give me you suggestion.
Check this code it help full to you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *isImgOfTable = [[self.listOfEvents objectAtIndex:indexPath.row] objectForKey:#"EventImage"];
NSString *CellIdentifier = #"Cell";
//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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgOfEvent = [[UIImageView alloc] init];
imgOfEvent.tag = 101;
[cell.contentView addSubview: imgOfEvent];
UILabel *lblEventTitle = [[UILabel alloc] init];
lblEventTitle.tag = 102;
[cell.contentView addSubview:lblEventTitle];
UILabel *lblDescription = [[UILabel alloc] init];
lblDescription.tag = 103;
[cell.contentView addSubview:lblDescription];
}
UIImageView *imgEvent = (UIImageView *) [cell.contentView viewWithTag:101];
imgEvent.hidden=YES;
if([isImgOfTable length] > 0)
{
NSString *newPath = #"";
imgEvent.hidden=NO;
imgEvent.userInteractionEnabled = YES;
newPath = [[GeneralClass getDocumentDirectory] stringByAppendingPathComponent:[[self.listOfEvents objectAtIndex:indexPath.row] objectForKey:#"EventImage"]];
imgEvent.frame = CGRectMake(mainX, 4, 45, 45);
imgEvent.backgroundColor = [UIColor colorWithRed:(187/255.f) green:(226/255.f) blue:(255/255.f) alpha:1.0f];
imgEvent.layer.cornerRadius = 7;
imgEvent.layer.borderColor = [UIColor colorWithRed:(224/255.f) green:(224/255.f) blue:(224/255.f) alpha:1.0f].CGColor;
imgEvent.layer.borderWidth = 1;
imgEvent.clipsToBounds = YES;
imgEvent.image = [UIImage imageWithContentsOfFile:newPath];
}
UILabel *lblEventTitle = (UILabel*) [cell.contentView viewWithTag:102];
.
.
// Code of UILabel *lblEventTitle
UILabel *lblEventDescription = (UILabel*) [cell.contentView viewWithTag:103];
.
.
// Code of UILabel *lblEventDescription
return cell;
}
Might i suggest subclassing UITableViewCell and using prepareForReuse
-(void)prepareForReuse
{
labelOne = #"Default text 1";
labelTwo = #"Default label 2";
[imageView setImage:nil]; //Or you could set a default image?
}

Create editable UITextView inside a UITableViewController cell

I created a uitextview inside a uitableviewcontroller programatically but i am unable to edit the textview. Here's an overview to my table layout:
Row1: UILabel
Row2: Uneditable UITextview
Row3: UILabel
Row4: Editable UITextview
Here's what i am doing:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UILabel *label = nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(indexPath.row%2==0)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 50)];
[label setBackgroundColor:[self.cellBackgroundColor objectAtIndex:indexPath.row]];
[label setText:[self.celltitle objectAtIndex:indexPath.row]];
label.font=[UIFont fontWithName:[self.cellFontName objectAtIndex:indexPath.row] size:[[self.cellFontSize objectAtIndex:indexPath.row] integerValue]];
label.textAlignment = NSTextAlignmentLeft;
[[cell contentView] addSubview:label];
}
else{
UITextView *messageBox= [[UITextView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 150)];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.userInteractionEnabled=YES;
if(indexPath.row==3)
{
[messageBox setEditable:YES];
[messageBox setUserInteractionEnabled:YES];
messageBox.delegate=self;
messageBox.editable=YES;
}
[cell.contentView addSubview: messageBox];
}
return cell;}
I have also set textviewdelegate in header file and textviewshouldbeginediting method but row4 textview is still not editable... Any help?
In addition to making the messageBox setEditable and setUserInteractionEnabled, you ALSO have to make sure those properties are enabled in your UITableViewController as well since the UITextView is nested within it!
[tableView setUserInteractionEnabled:YES];
[cell setUserInteractionEnabled:YES];
[messageBox setEditable:YES];
[messageBox setUserInteractionEnabled:YES];
(*Note, your tableView and TableViewCell both have the same name from this function so I would put that code elsewhere but I added it above just incase)
Try this.. May be it will help you..Its working for me
if(indexPath.row==3)
{
messageBox.delegate=self;
[messageBox setEditable:YES];
[messageBox setUserInteractionEnabled:YES];
messageBox.editable=YES;
[cell addSubview: messageBox];
}
I tried your code..Its working for me.. see the changes bellow
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UILabel *label = nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if(indexPath.row%2==0)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 50)];
[label setBackgroundColor:[self.cellBackgroundColor objectAtIndex:indexPath.row]];
[label setText:[self.celltitle objectAtIndex:indexPath.row]];
label.font=[UIFont fontWithName:[self.cellFontName objectAtIndex:indexPath.row] size:[[self.cellFontSize objectAtIndex:indexPath.row] integerValue]];
label.textAlignment = NSTextAlignmentLeft;
[[cell contentView] addSubview:label];
}
else{
UITextView *messageBox= [[UITextView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 100)];
cell.userInteractionEnabled=YES;
if(indexPath.row==1)
{
// Uneditable UITextview
messageBox.editable=NO;
}
[cell.contentView addSubview: messageBox];
}
}
return cell;
}
You have to initialize the cell´s content view before using it. Try this:
cell.contentView = [[UIView alloc] initWithFrame:CGRectMake(0,0,cell.frame.size.width, 150)];

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];
}

Resources