(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
dictionary = [QuestionMutableArray objectAtIndex:0];
static NSString *CellIdentifier = #"BeginingCell";
BeginingCell *cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:#"BeginingCell" owner:self options:nil ];
for(id CurrentObject in topLevelObjects)
{
if ([CurrentObject isKindOfClass:[BeginingCell class]]) {
cell=(BeginingCell *) CurrentObject;
break;
}
}
}
// Configure the cell.
if(indexPath.row==0)
{
cell.SectionTitle.text=[dictionary objectForKey:#"question"];
cell.Option1.text=[dictionary objectForKey:#"option1"];
cell.Option2.text=[dictionary objectForKey:#"option2"];
cell.Option3.text=[dictionary objectForKey:#"option3"];
cell.Option4.text=[dictionary objectForKey:#"option4"];
UIImage *imgDef=[UIImage imageNamed:#"man_kirstie_alley.jpg"];
[cell.myImageView setImage:imgDef];
[MyTestArray release];
[cell.button1 setTitle:#"A." forState:UIControlStateNormal];
[cell.button2 setTitle:#"B." forState:UIControlStateNormal];
[cell.button3 setTitle:#"C." forState:UIControlStateNormal];
[cell.button4 setTitle:#"D." forState:UIControlStateNormal];
}
return cell;
}
I think you must create a cell first. You could use a default cell like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
//---try to get a reusable cell---
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
//---create new cell if no reusable cell is available---
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
//---You would set the image here---
UIImage *imgDef=[UIImage imageNamed:#"man_kirstie_alley.jpg"];
cell.image = imgDef;
return cell;
Related
I have a problem that Im sure many objectiveC developers would be able to solve pretty easily. Im developing an app which is a dynamic tableview with different groups that the user can create. The user can enter a number of groups with different totals. I am trying to sum the total of all the groups created.
The IBAction I am using to calculate the subtotal is
- (IBAction)Calculate:(id)sender {
//---------------
NSInteger Tempsum = [[_dataArray valueForKeyPath:#"#sum.name2"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)Tempsum];
//--------------
}
I have created the following code in the .m file of my tableview and also created a NSArray property called;
#property NSArray *dataArray;
however I am unsure as to the correct code to use to be able to link the result ( #"#sum.name2" ) to the text value in the Tableviewcontroller ( _TotalAnimals.text)
Any help with this problem would be much appreciated. below is the full code for the .m file
#import "TSPViewController.h"
#import <CoreData/CoreData.h>
#import "TSPToDoCell.h"
#import "TSPAddToDoViewController.h"
#import "TSPUpdateToDoViewController.h"
int TempTotalAnimals = 0;
int TotalAnimals = 0;
int Tempsum = 0;
#interface TSPViewController () <NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSIndexPath *selection;
#property NSArray *dataArray;
#end
#implementation TSPViewController
#pragma mark -
#pragma mark View Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
// Initialize Fetch Request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"TSPItem"];
// Add Sort Descriptors
[fetchRequest setSortDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"createdAt" ascending:YES]]];
// Initialize Fetched Results Controller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
// Configure Fetched Results Controller
[self.fetchedResultsController setDelegate:self];
// Perform Fetch
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) {
NSLog(#"Unable to perform fetch.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"addToDoViewController"]) {
// Obtain Reference to View Controller
UINavigationController *nc = (UINavigationController *)[segue destinationViewController];
TSPAddToDoViewController *vc = (TSPAddToDoViewController *)[nc topViewController];
// Configure View Controller
[vc setManagedObjectContext:self.managedObjectContext];
} else if ([segue.identifier isEqualToString:#"updateToDoViewController"]) {
// Obtain Reference to View Controller
TSPUpdateToDoViewController *vc = (TSPUpdateToDoViewController *)[segue destinationViewController];
// Configure View Controller
[vc setManagedObjectContext:self.managedObjectContext];
if (self.selection) {
// Fetch Record
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:self.selection];
if (record) {
[vc setRecord:record];
}
// Reset Selection
[self setSelection:nil];
}
}
}
#pragma mark -
#pragma mark Fetched Results Controller Delegate Methods
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
switch (type) {
case NSFetchedResultsChangeInsert: {
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeDelete: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeUpdate: {
[self configureCell:(TSPToDoCell *)[self.tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
}
case NSFetchedResultsChangeMove: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (void)configureCell:(TSPToDoCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// Fetch Record
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Update Cell
[cell.nameLabel setText:[record valueForKey:#"name"]];
[cell.nameLabel2 setText:[record valueForKey:#"name2"]];
[cell.doneButton setSelected:[[record valueForKey:#"done"] boolValue]];
[cell setDidTapButtonBlock:^{
BOOL isDone = [[record valueForKey:#"done"] boolValue];
// Update Record
[record setValue:#(!isDone) forKey:#"done"];
}];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
if (record) {
[self.fetchedResultsController.managedObjectContext deleteObject:record];
}
}
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Store Selection
[self setSelection:indexPath];
// Perform Segue
[self performSegueWithIdentifier:#"updateToDoViewController" sender:self];
}
// NSArray Below============
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *sections = [self.fetchedResultsController sections];
id<NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TSPToDoCell *cell = (TSPToDoCell *)[tableView dequeueReusableCellWithIdentifier:#"ToDoCell" forIndexPath:indexPath];
// Configure Table View Cell
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (IBAction)Calculate:(id)sender {
//---------------
NSInteger Tempsum = [[_dataArray valueForKeyPath:#"#sum.name2"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)Tempsum];
//--------------
}
/*
//---------------
NSInteger TempsumTotalAnimals = [[_charactersArray valueForKeyPath:#"#sum.passenger"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)TempsumTotalAnimals];
//--------------
*/
#end
I wrote the following code to make my cell transparent as I do with UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Nsubject";
SubjectsCell *cell = (SubjectsCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"mySubjectCell" owner:self options:nil];
cell=subjCell;
UIView* backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];
cell.backgroundView = backgroundView;
for ( UIView* view in cell.contentView.subviews )
{
view.backgroundColor = [ UIColor clearColor ];
}
}
[cell SetTitle:[subjectsArr objectAtIndex:indexPath.row]];
return cell;
}
anybody can help me
In viewDidLoad you can simply add
self.tableView.backgroundColor = [UIColor clearColor];
You do not need to make your own view like you have above.
I have a one Tableview in that i added a UIButton to each Tableviewcell named it as Remove
when i click the remove button the appropriate cell data will be remove from the tableview
and i added UIButton programmatically
now i want to perform remove option.
Thanks in Advance....
try this one:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *s = #"cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:s];
AsyncImageView *asyncImage;
UIButton *button = nil;
if ( cell == nil ) {
cell = [[[UITableViewCell alloc]initWithReuseIdentifier:s] autorelease];
UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:#selector(remove:)
forControlEvents:UIControlEventTouchUpInside];
….
[cell addSubview:button];
}
…..
return cell;
}
-(void)remove:(UIButton*)btn{
UITableViewCell *cell = (UITableViewCell *)btn.superview;
NSIndexPath* index = [self.tableView indexPathForCell:cell];
[peopleList removeObjectAtIndex:index.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:index]
withRowAnimation:UITableViewRowAnimationRight];
}
I want to add simple search bar in the table view. Program getting run with no error, but when I try to add text in search bar, program gets terminates
following is my code:
#interface RootViewController : UITableViewController<UISearchBarDelegate> {
NSArray *list;
IBOutlet UISearchBar *searchBar;
NSMutableArray *searchresult;
BOOL isSearchon;
BOOL canSelectRow;
}
#property(nonatomic, retain)NSArray *list;
#property(nonatomic, retain)IBOutlet UISearchBar *searchBar;
-(void)doneSearching:(id)sender;
-(void)searchlist;
#end
//in .m
#implementation RootViewController
#synthesize list,searchBar;
-(void)doneSearching:(id)sender
{
isSearchon=NO;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
self.navigationItem.rightBarButtonItem=nil;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}
-(void)searchlist
{NSString *searchText = searchBar.text;
[searchresult removeAllObjects];
for(NSString *str in list)
{
NSRange titleResultsRange=[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchresult addObject:str];
}
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchlist];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if([searchText length]>0)
{isSearchon =YES;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
[self searchlist];}
else{
isSearchon =NO;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
}
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
list = [[NSArray alloc]initWithObjects:#"rohan",#"vidhya",#"kavita",#"pushkar",nil];
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType=UITextAutocorrectionTypeYes;
searchresult=[[NSMutableArray alloc]init];
isSearchon =NO;
canSelectRow=YES;
self.navigationItem.title = #"Names";
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearchon =YES;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneSearching:)]autorelease];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isSearchon){
return [searchresult count];}
else{
return [list count];}
}
// Customize the appearance of table view cells.
- (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] autorelease];
}
if(isSearchon)
{
cell.text=[searchresult objectAtIndex:indexPath.row];}
else{
cell.text=[list objectAtIndex:indexPath.row];}
// Configure the cell.
return cell;
}
- (void)dealloc {
[super dealloc];
[searchBar release];
}
#end
I have edited my code in my question...it works fine nw....AnyOne willing to use searchbar in tableview in Iphones can refer the code.
I have an app that has a tab bar, each tab contains a separate table. The first table uses core data to persist its entries and checkmarks. The second table on the second tab uses an NSMutableArray to populate it (I would use core data but I would have to pre populate it and this table does not allow that) I would like to persist check marks the same way I do in the first table with core data but something is wrong. The code looks like this:
-(void)viewDidLoad {
[super viewDidLoad];
airport = [[NSMutableArray alloc] init];
[airport addObject:#"Passport"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [airport count];
}
// Customize the appearance of table view cells.
- (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] autorelease];
}
// Set up the cell...
NSString *cellValue = [airport objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
//[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSManagedObject *item = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = [item valueForKey:#"name"]; //CHANGED TO DETAIL
if ([[item valueForKey:#"check"] boolValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([[selectedObject valueForKey:#"check"] boolValue]) {
[selectedObject setValue:[NSNumber numberWithBool:NO] forKey:#"check"];
} else {
[selectedObject setValue:[NSNumber numberWithBool:YES] forKey:#"check"];
}
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone) {
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
thisCell.accessoryType = UITableViewCellAccessoryNone;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
I believe the line cell.textLabel.text = [item valueForKey#"name"];
is whats causing it. All that I would like for this to do is have the table populated from the array and check marks persisted. Any help is GREATLY appreciated. Thanks in advance.
This line is replacing the cell text:
cell.textLabel.text = [item valueForKey:#"name"];
that was initially assigned by these lines:
NSString *cellValue = [airport objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
Why are your using the "name" property of "item"?