When using reloading with indexpaths or indexsets the _recordLabel and _dateLabel are shown, and then not shown, and it repeats again. Im using the debug paint layers and its nowhere around. But if use reload data everything seems fine. I don't know why is that happening.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier;
cellIdentifier = [_sections objectAtIndex:indexPath.section];
XFitGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[XFitGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[self stampCell:cell atIndexPath:indexPath];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)stampCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier isEqualToString:#"exerciseDescriptionCell"]) {
if (!_textView) {
_textView = [[UITextView alloc] initWithFrame:CGRectMake(0.f, 22.f, cell.frame.size.width, 66.f)];
}
_textView.editable = NO;
_textView.font = [UIFont fontWithName:#"Avenir-Light" size:14.f];
[cell.contentView addSubview:_textView];
}
else if ([cell.reuseIdentifier isEqualToString:#"exerciseResultsCell"]) {
UILabel *recordLabelTag = [[UILabel alloc] initWithFrame:CGRectMake(10.f, 28.f, 55.f, 14.f)];
if ([_exercise.eType.name isEqualToString:#"Strength"]) {
recordLabelTag.text = #"PR";
}
else {
recordLabelTag.text = #"UB";
}
recordLabelTag.font = [UIFont fontWithName:#"Avenir-Heavy" size:14.f];
recordLabelTag.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:recordLabelTag];
if (!_recordLabel) {
_recordLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.f, 48.f, 55.f, 12.f)];
}
_recordLabel.font = [UIFont fontWithName:#"Avenir-Light" size:12.f];
_recordLabel.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:_recordLabel];
UILabel *dateLabelTag = [[UILabel alloc] initWithFrame:CGRectMake(70.f, 28.f, 55.f, 14.f)];
dateLabelTag.text = #"Date";
dateLabelTag.font = [UIFont fontWithName:#"Avenir-Heavy" size:14.f];
dateLabelTag.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:dateLabelTag];
if (!_dateLabel) {
_dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(70.f, 48.f, 55.f, 12.f)];
}
_dateLabel.font = [UIFont fontWithName:#"Avenir-Light" size:12.f];
_dateLabel.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:_dateLabel];
UIButton *recordButton = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - 73.f, 30.f, 65.f, 28.f)];
recordButton.backgroundColor = [UIColor colorWithRed:77.f/255.f green:123.f/255.f blue:209.f/255.f alpha:1.f];
recordButton.layer.cornerRadius = 4.f;
[recordButton addTarget:self action:#selector(addRecord) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:recordButton];
UILabel *newPRLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.f, 7.f, 55.f, 14.f)];
if ([_exercise.eType.name isEqualToString:#"Strength"]) {
newPRLabel.text = #"New PR";
}
else {
newPRLabel.text = #"New UB";
}
newPRLabel.textColor = [UIColor whiteColor];
newPRLabel.font = [UIFont fontWithName:#"Avenir-Book" size:14.f];
[recordButton addSubview:newPRLabel];
UIButton *showAllButton = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - 73.f - 75.f, 30.f, 65.f, 28.f)];
showAllButton.backgroundColor = [UIColor colorWithRed:98.f/255.f green:233.f/255.f blue:126.f/255.f alpha:1.f];
showAllButton.layer.cornerRadius = 4.f;
[cell.contentView addSubview:showAllButton];
UILabel *showAllLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.f, 7.f, 55.f, 14.f)];
showAllLabel.text = #"Show All";
showAllLabel.textColor = [UIColor whiteColor];
showAllLabel.font = [UIFont fontWithName:#"Avenir-Book" size:14.f];
[showAllButton addSubview:showAllLabel];
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier isEqualToString:#"exerciseDescriptionCell"]) {
[(XFitGroupCell *)cell setText:#"Description"];
[(XFitGroupCell *)cell setImage:[UIImage imageNamed:#"descriptionIcon"]];
_textView.text = _exercise.overview;
}
else if ([cell.reuseIdentifier isEqualToString:#"exerciseResultsCell"]) {
[(XFitGroupCell *)cell setText:#"Previous Results"];
[(XFitGroupCell *)cell setImage:[UIImage imageNamed:#"recordIcon"]];
ExerciseRecord *personalRecord = _exercise.personalRecord;
NSLog(#"Received: %#\n", personalRecord.score);
_recordLabel.text = [personalRecord.score stringValue];
NSLog(#"Text : %#\n", _recordLabel.text);
_dateLabel.text = [_dateFormatter stringFromDate:personalRecord.date];
}
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return 88.f;
}
else if (indexPath.section == 1) {
return 66.f;
}
return 0.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 15.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 7.f;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1) {
if (buttonIndex == 1) {
ExerciseRecord *eRecord = [NSEntityDescription insertNewObjectForEntityForName:#"ExerciseRecord" inManagedObjectContext:_managedObjectContext];
eRecord.score = [NSNumber numberWithInt:[[alertView textFieldAtIndex:0].text intValue]];
eRecord.date = [NSDate date];
eRecord.exercise = _exercise;
NSError *error;
if (![_managedObjectContext save:&error]) {
NSLog(#"%# %#", error, [error userInfo]);
abort();
}
[_tableView reloadData];
//[_tableView beginUpdates];
//[_tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
//[_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
//[_tableView endUpdates];
}
}
}
I am not sure why this isn't working, but from my experience I'd recommend you use a framework while working with Core Data instead of doing all the work manually yourself. I personally use the Sensible TableView framework, which automatically fetches my data and displays it in table views. It also handles all entity relationships and auto creates the detail views for them. Saves me tons of development time when working on Core Data projects. HTH.
Related
I am trying to create an expandable table view, however when I click on one of the cells I load a .xib file to format the subviews, however when I click the cell again the .xib format remains and messes with the view of the cells. Is there a better way to make the expandable table view?
Code:
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 28;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:tableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return [ticketList count];
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 72;
}
Load the xib here:
- (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:#"reuse"];
}
// Configure the cell...
NSLog(#"Number: %d", indexPath.section);
NSArray *items = [[NSArray alloc] initWithObjects:#"Cleanliness", #"Door", #"Peek Hole", #"Sink", #"Towel Rack", #"Closet", #"Carpet", #"Wall", #"Bed", #"Matress", #"Mattress Cover", #"Fridge", #"Blinds", #"Window", #"Screen", #"Air Conditioning", #"Chair", #"Desk", #"Garbage bin", #"Shelves", #"Phone", #"Jacks", #"Lights", #"Smoke Detector", #"Heat Detector", #"Light bulb", #"Deep Cleaning", #"Final Prep", nil];
if (!indexPath.row)
{
// first row
cell.textLabel.text = items[indexPath.section]; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
}
else
{
}
}
else
{
[self.tableView registerNib:[UINib nibWithNibName:#"HelpDeskCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
HelpDeskCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[HelpDeskCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
CGFloat fontsize = 16;
if([[[ticketList objectAtIndex:indexPath.row] objectForKey:#"priority"] isEqualToString:#"Critical"]){
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.5 alpha:1.0]];
}
else{
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:0.925 green:0.925 blue:0.925 alpha:1.0]];
}
[cell.IDLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
//reduce fontsize to 12 for the information labels
//same on all devices and orientations
fontsize = 12;
//ticket status label
[cell.statusLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.statusLabel setTextColor:[UIColor whiteColor]];
//ticket category label
[cell.categoryLabel setBackgroundColor:[UIColor grayColor]];
[cell.categoryLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.categoryLabel setTextColor:[UIColor whiteColor]];
//ticket title label
[cell.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.titleLabel setTextColor:[UIColor blackColor]];
//Label holds the user that submitted the ticket
[cell.submittedLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.submittedLabel setTextColor:[UIColor blackColor]];
//Label holds the user currently working on the ticket
[cell.handleLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.handleLabel setTextColor:[UIColor blackColor]];
//ticket date label
[cell.dateLabel setFont:[UIFont systemFontOfSize:fontsize]];
// Set the text of the subviews
NSString * ticketIdStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"ticket_id"];
[cell.IDLabel setText:ticketIdStr];
NSString * ticketStatusStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"status"];
[cell.statusLabel setText:ticketStatusStr];
if([ticketStatusStr isEqualToString:#"Open"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0 green:0.6 blue:0.8 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"In Progress"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:1.0 green:0.733 blue:0.2 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Resolved"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.6 green:0.8 blue:0 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Closed"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1.0]];
}
NSString * categoryStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"category"];
[cell.categoryLabel setText:categoryStr];
NSString * titleStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString * userIDStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"user_id"];
NSString * handledByStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"handled_by"];
[cell.titleLabel setText: [NSString stringWithFormat:#"Title: %#", titleStr]];
[cell.submittedLabel setText: [NSString stringWithFormat:#"Submitted By: %#", userIDStr]];
[cell.handleLabel setText: [NSString stringWithFormat:#"Handled By: %#", handledByStr]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *orignalDate = [dateFormatter dateFromString:[[[ticketList objectAtIndex:indexPath.row] objectForKey:#"date_submitted"] substringToIndex:10]];
[dateFormatter setDateFormat:#"MMMM dd, yyyy"];
NSString * ticketDateStr = [dateFormatter stringFromDate:orignalDate];
[cell.dateLabel setText:ticketDateStr];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
return cell;
}
Expand and Collapse here:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
[self.tableView reloadData];
}
}
Update
The main cell is a list of items and the expanding cell is suppose to be tickets from a sql database. I use a xib file to format the tickets
but when I collapse the cell which contains the items, this image remains and covers up the item cells
For creating expandable table view on clicking of UITableViewCell simply add a new cell in existing UITableView
[self.tableview insertRowsAtIndexPath:indexPath
withRowAnimation:UITableViewRowAnimationAutomatic];
I am new in iOS developer. When I run the the app than time iI
but I will get this type of output.
Here is my code
- (void) iterateItems:(NSArray*) array
{
level++;
for (int i = 0; i < [array count]; i++)
{
commentInfo = [array objectAtIndex:i];
//NSLog(#"data=%#",commentInfo);
Item *item = [[Item alloc] init];
item.Id = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
item.parentId = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
if (item.level == 0)
{
item.title =[commentInfo objectForKey:#"dates"];
item.title1 =[commentInfo objectForKey:#"id"];
}
else
{
item.title=#"abc";
}
//NSLog(#"title is=%#",[commentInfo objectForKey:#"status"]);
item.level = level;
item.visibility = #"normal";
item.childVisibility = #"normal";
[items addObject:item];
[self iterateItems:[commentInfo objectForKey:#"sub_items"]];
}
level--;
}
- (float) cellHeightForRow:(int) row
{
Item *item = [items objectAtIndex:row];
if ([item.visibility isEqualToString:#"hidden"])
{
return 0.0f;
}
else
{
return 50.0f;
}
}
- (void) hideCompleteNode:(UISwipeGestureRecognizer*) gestureRecognizer
{
UITableViewCell *cell = (UITableViewCell*) [[gestureRecognizer view] superview];
NSIndexPath *indexPath = [self.tblView indexPathForCell:cell];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
if ([item.childVisibility isEqualToString:#"normal"])
{
[self hideChilds:indexPath];
}
}
else
{
int prevIndex = indexPath.row-1;
if (prevIndex >= 0)
{
Item *parentItem = [items objectAtIndex:prevIndex];
while (parentItem.level != 0)
{
prevIndex--;
if (prevIndex >= 0)
parentItem = [items objectAtIndex:prevIndex];
else
break;
}
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:prevIndex inSection:0];
[self hideChilds:indexPath];
}
}
- (void) hideChilds:(NSIndexPath*) indexPath
{
NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithObjects:indexPath, nil];
Item *item = [items objectAtIndex:indexPath.row];
BOOL shouldHide = [item.childVisibility isEqualToString:#"hidden"]?NO:YES;
item.childVisibility = shouldHide?#"hidden":#"normal";
int nextIndex = indexPath.row+1;
if (nextIndex < [items count])
{
Item *childItem = [items objectAtIndex:nextIndex];
while (childItem.level > item.level)
{
childItem.visibility = shouldHide?#"hidden":#"normal";
childItem.childVisibility = shouldHide?#"hidden":#"normal";
[indexPaths addObject:[NSIndexPath indexPathForRow:nextIndex inSection:0]];
nextIndex++;
if (nextIndex < [items count])
childItem = [items objectAtIndex:nextIndex];
else
break;
}
}
[self.tblView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark -
#pragma mark - UITableView Datasource and Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellHeightForRow:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"itemCell";
UITableViewCell *cell = [self.tblView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
UIImageView *arrowImgView = [[UIImageView alloc] init];
[arrowImgView setBackgroundColor:[UIColor clearColor]];
[arrowImgView setTag:1];
[cell.contentView addSubview:arrowImgView];
UILabel *titleLbl = [[UILabel alloc] init];
[titleLbl setFont:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]];
[titleLbl setTextColor:[UIColor blackColor]];
titleLbl.textAlignment = NSTextAlignmentCenter;
[titleLbl setTag:2];
[titleLbl setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:titleLbl];
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(hideCompleteNode:)];
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionLeft];
[cell.contentView addGestureRecognizer:swipeGesture];
}
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
[cell.contentView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"cell_background.png"]]];
}
else
{
[cell.contentView setBackgroundColor:[UIColor clearColor]];
}
UIImageView *arrowImgView = (UIImageView*) [cell viewWithTag:1];
UILabel *titleLbl = (UILabel*) [cell viewWithTag:2];
if ([item.visibility isEqualToString:#"hidden"])
{
[titleLbl setFrame:CGRectZero];
[arrowImgView setFrame:CGRectZero];
}
else
{
[arrowImgView setFrame:CGRectMake(5.0f+(20.0f*item.level), 20.0f, 10.0f, 10.0f)];
if ([item.childVisibility isEqualToString:#"hidden"])
{
[arrowImgView setImage:[UIImage imageNamed:#"closeArrow"]];
}
else
{
[arrowImgView setImage:[UIImage imageNamed:#"openArrow"]];
}
[titleLbl setFrame:CGRectMake(20.0f+(20.0f*item.level), 10.0f, 320.0f - (20.0f+(20.0f*item.level)), 30.0f)];
[titleLbl setText:item.title];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.layer.shadowOpacity = 0.3;
cell.layer.shadowColor = [UIColor blueColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0.0, 4);
[tblView setSeparatorColor:[UIColor redColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
[tblView setSeparatorColor:[UIColor blackColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
// [self hideChilds:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[self.tblView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:0.004 green:0.482 blue:0.776 alpha:1];
[self hideChilds:indexPath];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
}
else
{
Item *item = [items objectAtIndex:indexPath.row];
NSLog(#"value=%#",[NSString stringWithFormat:#"%#",item.title1]);
approveleaseoffer *secondViewController =
[self.storyboard instantiateViewControllerWithIdentifier:#"approveleaseofferpage"];
secondViewController.offer_number=[NSString stringWithFormat:#"%#",item.title1];
[self.navigationController pushViewController:secondViewController animated:YES];
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
-(void)viewDidLayoutSubviews
{
if ([tblView respondsToSelector:#selector(setSeparatorInset:)]) {
[tblView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tblView respondsToSelector:#selector(setLayoutMargins:)]) {
[tblView setLayoutMargins:UIEdgeInsetsZero];
}
}
Try changing the line item.childVisibility = #"normal"; to item.childVisibility = #"hidden";
in iterateItems method.
I am creating multiple lists like questions and answer session, question with multiple answers in table rows. But whenever I select a row other questions answers are also get selected and when I came back to same all the selections are gone. So how to avoid this ? Please help.
my code is,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(val==1)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<17; i++)
{
[checkedArr addObject:#"1"];
}
NSLog(#"Checked arr size %i",[checkedArr count]);
return 17;
}
else if(val==2)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<13; i++)
{
[checkedArr addObject:#"1"];
}
return 13;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%i",indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:99/255.0f green:209/255.0f blue:248/255.0f alpha:1.0];
cell.selectedBackgroundView = selectionColor;
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView.hidden=TRUE;
//cell.accessoryView=Nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[checkedArr count]);
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[questionTable cellForRowAtIndexPath:indexPath];
[checkedArr replaceObjectAtIndex:indexPath.row withObject:#"0"];
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView=nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
[questionTable deselectRowAtIndexPath:indexPath animated:YES];
//[self.questionTable reloadData];
NSLog(#"Val is %i",val);
NSLog(#"selected is %#",[listArray objectAtIndex:indexPath.row]);
// NSLog(#"Checked arr descripton %#",[checkedArr description]);
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryView = nil;
}
How I can add prefix tel:65 to my phone number, that I fetched from address book in array.
If I do this in viewdidload it's getting null
NSURL *phoneUrl = [NSURL URLWithString:[NSString stringWithFormat:#"tel:%#", phoneNumbers]];
NSLog(#"Some Text %#", phoneUrl);
NSLog(#"Phone Numbers %#", phoneNumbers);
Here phoneNumbers is array with numbers per each contact
Udate:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"BG.jpg"]]];
[detailTableView setBackgroundColor:[UIColor clearColor]];
detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
ShadowTable *Shadow = [[ShadowTable alloc] init];
[Shadow ForTableView:detailTableView ForView:self.view HeaderAlpha:0.3 FooterAlpha:0.6];
for(int i = 0 ; i <[phoneNumbers count]; i++)
{
NSURL *phoneUrl = [NSURL URLWithString:[NSString stringWithFormat:#"tel:%#", [phoneNumbers objectAtIndex:i]]];
NSLog(#"Phone with URL %#", phoneUrl);
NSLog(#"Phone Numbers %#", phoneNumbers);
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [phoneTypes count];
}
- (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];
}
UILabel *typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
typeLabel.text = [phoneTypes objectAtIndex:indexPath.row];
[typeLabel setBackgroundColor:[UIColor clearColor]];
[cell addSubview:typeLabel];
UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 10, 170, 40)];
numberLabel.text = [phoneNumbers objectAtIndex:indexPath.row];
[numberLabel setBackgroundColor:[UIColor clearColor]];
[cell addSubview:numberLabel];
if (indexPath.row %2 == 0) {
cell.contentView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
} else {
cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
}
//cell.textLabel.text = [phoneNumbers objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
You are using an array not a string. So you need to access all elements of array to add as suffix.
Use this :
for(int i = 0 ; i <[phoneNumbers count]; i++)
{
NSString *str = [#"tel:" stringByAppendingFormat:#"%#",[phoneNumbers objectAtIndex:i]];
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *phoneUrl = [NSURL URLWithString:str];
NSLog(#"Some Text %#", phoneUrl);
}
EDIT : Url was null because there were spaces in "2013-05-31 14:58:24.759 GTCallBack[8225:c07]" so encode it to remove spaces.
Hope it helps you.
I try to make a little program to learn more about searching a tableview about a searchbar. Meanwhile i'm in the third week trying to do this. I found many examples in different ways in the internet. The most with a searchdisplaycontroller but this way is only for a viewcontroller. i prefer a way that also works with an uiview and so i use the searchbar delegatemethod to filter my data dictionary. Normally i try as long i get handle such things by myself. But this is my nemesis. I really can't find a way to get this problem solved. Can anyone help me with my code?
Here it is.
#import "FilterDemoTableViewController.h"
#implementation FilterDemoTableViewController
#synthesize filteredTableData;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize tableContents;
#synthesize Keys;
- (void)viewDidLoad
{
[super viewDidLoad];
searchBar.delegate = (id)self;
//-----------------------My TableView Data ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
//--------------------------------------------------------------------------
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered) {
return [filteredTableData count];
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
int rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = [listData count];
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSDictionary* sectionDictionary;
if (isFiltered) {
sectionDictionary = [filteredTableData objectAtIndex:indexPath.section];
} else {
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
}
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
//I think here is something wrong but i don't know what
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in tableContents) //dictionary read
{
NSArray *array = [dictionary objectForKey:Keys]; //section of dictionary read
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
[filteredTableData addObject:sTemp];
}
}
[self.tableView reloadData];
}
- (void)viewDidUnload{
[self setSearchBar:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Now i post a complete refreshed code. I tested each component of the code step by step. It works and the search is also fine (in a UITableViewController). But in this example the hole code is in a UIView. The reason, on this way it is possible to create non full-size tableviews and instanzes of tableviews. Much better for a clear Viewcontroller. I know that an UIView has no method like this reloadData but it is necessary.
Near the code end you can see the problem line. And for this last step i have no idea how i can solve this. [self.tableView reloadData];
#import "TableView.h"
#import <QuartzCore/QuartzCore.h>
#interface TableView ()
#end
#implementation TableView
#synthesize delegate;
#synthesize dropDownHeight;
#synthesize labelText;
#synthesize enabled;
#synthesize tableContents;
#synthesize Keys;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize filteredTableData;
- (void)__show {
viewControl.alpha = 0.0f;
UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
[mainWindow addSubview:viewControl];
[UIView animateWithDuration:0.3f
animations:^{
viewControl.alpha = 1.0f;
}
completion:^(BOOL finished) {}];
}
- (void)__hide {
[UIView animateWithDuration:0.2f
animations:^{
viewControl.alpha = 0.0f;
}
completion:^(BOOL finished) {
[viewControl removeFromSuperview];
}];
}
- (void) setLabelText:(NSString *)_labelText{
[button setTitle:labelText forState:UIControlStateNormal];
}
- (void) setEnable:(BOOL)_enabled{
enabled = _enabled;
[button setEnabled:_enabled];
}
- (void) setArrayData:(NSArray *)_arrayData{
[table reloadData];
}
- (void) buttonPressed{
[self __show];
}
- (void) controlPressed{
//[viewControl removeFromSuperview];
[self __hide];
}
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(10, 0, 280, 30)];
[button setTitle:#"--Auswahl--" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"combo_bg.png"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:14]];
[self addSubview:button];
dropDownHeight = 706;
viewControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
[viewControl addTarget:self action:#selector(controlPressed) forControlEvents:UIControlEventTouchUpInside];
CGFloat x = self.frame.origin.x;
CGFloat y = (viewControl.frame.size.height - dropDownHeight)/2;
table = [[UITableView alloc] initWithFrame:CGRectMake(x, y, frame.size.width, dropDownHeight) style:UITableViewStyleGrouped];
table.dataSource = self;
table.delegate = self;
searchBar = [[UISearchBar alloc] init];
[searchBar sizeToFit];
searchBar.delegate = (id)self;
table.tableHeaderView = searchBar;
CALayer *layer = table.layer;
layer.masksToBounds = YES;
layer.cornerRadius = 2.0f;
layer.borderWidth = 1.0f;
[layer setBorderColor:[UIColor darkGrayColor].CGColor];
[viewControl addSubview:table];
CGAffineTransform rotateTable = CGAffineTransformMakeRotation(M_PI_2);
table.transform = rotateTable;
table.frame = CGRectMake(-2, -1, table.frame.size.width, table.frame.size.height);
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"gradientBackground.png"]];
[tempImageView setFrame:self->table.frame];
table.backgroundView = tempImageView;
//----------------------- TableView Daten ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",#"Hamburg",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
// ---------------------------------------------------------------------
}
return self;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
return 40;
}
else {
return 0;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(20, 6, 300, 30);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
label.shadowColor = [UIColor grayColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
[view addSubview:label];
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
return [self.Keys objectAtIndex:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered)
{
return 1;
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self.isFiltered)
{
rowCount = [filteredTableData count];
}
else
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
rowCount = [listData count];
}
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
if (isFiltered)
{
NSString * stadt = [filteredTableData objectAtIndex:indexPath.row];
cell.textLabel.text = stadt;
}
else
{
NSDictionary* sectionDictionary;
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:[indexPath section]]];
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedIndex = [indexPath row];
[self __hide];
[button setTitle:[[NSString alloc] initWithFormat:rowValue] forState:UIControlStateNormal];
}
- (NSInteger) selectedIndex {
return selectedIndex;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
[filteredTableData removeAllObjects];
for (NSString* key in self.tableContents)
{
NSArray *staedte = [self.tableContents objectForKey:key];
for (NSString *stadt in staedte)
{
NSRange titleResultsRange = [stadt rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
{
[filteredTableData addObject:stadt];
}
}
}
}
[self.tableView reloadData]; //Here is the error
}
-(void)didChangeTableViewValue:(TableView *)TableView selectedIndex:(NSInteger)selectedIndex {
}
#end