On my xcode project I have a view with a tableview. I also have a "special" string that contains the objects to populate the array that populates the tableview.
Example:
NSString *myValues=[[NSString alloc]init];
myValues = #"aaa$bbb$ccc?111$222$333?";
as you can see the characters $ and ? separate the objects.
When I call the view I populate the array by the string but the tableview doesn't work. Here some code:
File.H:
#import <UIKit/UIKit.h>
#interface EquipaggioVC : UIViewController <UITableViewDelegate, UITableViewDataSource>{
UITableView *tableViewEquipaggio;
UITableViewCell *nibLoadedCell;
NSMutableArray *arrayEquipaggio;
NSString *stringaDati;
}
#property (nonatomic, retain) IBOutlet UITableView *tableViewEquipaggio;
#property (nonatomic, retain) IBOutlet UITableViewCell *nibLoadedCell;
#property (nonatomic, retain) NSMutableArray *arrayEquipaggio;
#property (nonatomic, retain) NSString *stringaDati;
#end
File.M:
#import "EquipaggioVC.h"
#import "AppDelegate.h"
#import "ClassEquipaggio.h"
#interface EquipaggioVC ()
#end
#implementation EquipaggioVC
#synthesize tableViewEquipaggio;
#synthesize nibLoadedCell;
#synthesize arrayEquipaggio;
#synthesize stringaDati;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(NSString *)uuid
{
//to create an ID
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return [(NSString *)uuidStringRef autorelease];
}
-(void)loadTestData:(NSString*)stringaDatiArray{
//populate the array by the string.
if(stringaDatiArray!=nil){
NSArray *elenco=[stringaDatiArray componentsSeparatedByString:#"?"];
for (int i=0; i<([elenco count]-1) ; i++) {
NSString *dettagliEquipaggio=[[NSString alloc]init];
dettagliEquipaggio=[elenco objectAtIndex:i];
NSArray *dettagli=[dettagliEquipaggio componentsSeparatedByString:#"$"];
ClassEquipaggio *aEquipaggio=[[ClassEquipaggio alloc]init];
aEquipaggio.idMembro=[dettagli objectAtIndex:0];
aEquipaggio.sessoMembro=[dettagli objectAtIndex:1];
aEquipaggio.dataNascitaMembro=[dettagli objectAtIndex:2];
[arrayEquipaggio addObject:aEquipaggio];
[aEquipaggio release];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableEquipaggioView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
static NSString *sLoadNibNamed;
UITableViewCell *cell;
ClassEquipaggio *aEquipaggio=[arrayEquipaggio objectAtIndex:indexPath.row];
cell = [tableEquipaggioView dequeueReusableCellWithIdentifier:CellIdentifier];
sLoadNibNamed=#"EquipaggioCell";
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:sLoadNibNamed owner:self options:NULL];
cell = [self typeNibLoadCell:aEquipaggio.idMembro];
}
// Configure the cell
UILabel *tipoSessoLabel = (UILabel*) [cell viewWithTag:1];
tipoSessoLabel.text = aEquipaggio.sessoMembro;
UILabel *dataNascitaLabel=(UILabel*)[cell viewWithTag:2];
dataNascitaLabel.text=aEquipaggio.dataNascitaMembro;
return cell;
}
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
return [arrayEquipaggio count];
}
-(UITableViewCell *)typeNibLoadCell:(NSString *)named{
return nibLoadedCell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (void)viewDidLoad
{
[super viewDidLoad];
arrayEquipaggio=[[NSMutableArray alloc]init];
stringaDati=[[NSString alloc]init];
tableViewEquipaggio=[[UITableView alloc]init];
}
-(void)viewDidAppear:(BOOL)animated{
AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
UIBarButtonItem * btnIndietroa = [[[UIBarButtonItem alloc] initWithTitle:#"Indietro"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(editNavButtonPressed)]autorelease];
[self.navigationItem setLeftBarButtonItem:btnIndietroa];
stringaDati = [[NSUserDefaults standardUserDefaults] objectForKey:#"stringaDati"];
if(stringaDati!=nil){
[arrayEquipaggio removeAllObjects];
[self loadTestData:stringaDati];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)dealloc{
[super dealloc];
}
#end
On nib file the tableview has the connection with the delegate and datasource, as the IBoutlet is connected with it.
Thanks for your support.
EDIT: [arrayEquipaggio count] return 0.
By the looks of your question your problem is that the method cellForRowAtIndexPath is not being called and as you said the [arrayEquipaggio count] return 0.
Since you are using that array at the method numberOfRowsInSection with a return value of 0 is normal that your table is not calling the method cellForRowAtIndexPath. Since you are telling to your table that there are no rows.
If you want your table to be populated then check that your array return a value greater than 0.
In a nutshell It has no data to populate your table, that why it doesnt work.
Check that in your viewDidAppear:(BOOL)animated that your are pulling anything to stringaDati.
NSLog(#"info: %#",stringaDati);
Related
I'm having an issue with displaying cells in my UITableViewController, simply..nothing shows up when I go to test. Below is my code.
FormationViewController.m
#import <Foundation/Foundation.h>
#import "FormationViewController.h"
#interface FormationViewController ()
#end
#implementation FormationViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Title"
forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Title"];
}
NSString *name = _names[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", name];
return cell;
}
- (void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = #"Formation View";
self.tabBarItem.image = [UIImage imageNamed:#"tab_icon_formation"];
self.names = #[#"John Doe", #"Lee Harvey Oswald", #"Pat Buchanan", #"Angry Orchard",
#"Sierra Nevad", #"Jeff Bridges", #"John McClain", #"Lucy Genero"];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"The length of names is %lu", self.names.count);
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
self.formationVC.frame = CGRectMake(
0,
self.topLayoutGuide.length,
CGRectGetWidth(self.view.frame),
CGRectGetHeight(self.view.frame)
- self.topLayoutGuide.length
- self.bottomLayoutGuide.length
);
}
- (void)loadView {
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor whiteColor];
self.formationVC = [[UIView alloc] init];
self.formationVC.backgroundColor = [UIColor whiteColor];
[view addSubview:self.formationVC];
self.view = view;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
#end
And my FormationViewController.h
#import <UIKit/UIKit.h>
#interface FormationViewController : UITableViewController
#property (strong, nonatomic) UIView *formationVC;
#property (strong, nonatomic) NSArray *names;
#end
I'm also not sure if I'm putting some of these lines of code in the right methods.
I also think that my problem might be lying in the tableView:cellForRowAtIndexPath: method. I'm not absolutely sure I'm implementing that 100% correctly.
If anyone can help me find out what I'm doing wrong please let me know. This is my first Obj-C/iOS project I'm working on too so please be gentle! Thank you!
Well, I tried your code , using no xibs and faced the same problem.
Then I changed 2 things
removed LoadView.
moved self.names intialization from initWithNibName to viewDidLoad
added
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Title"];
[self.tableView reloadData];
to viewDidload
And it worked
I think you' re never stop in (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ... if you instantiate your view controller from a storyboard, you need to implement initWithCoder, or just put your names initialization in viewDidLoad.
As you are probably using Storyboard, check these steps:
1) Storyboard - select your table view controller and in Identity Inspector make sure you have it's class set to your FormationVC.
2) Storyboard - select table view inside the controller and select it's first cell (suggesting you use Prototype Cells). Make sure it's style is set to Basic and set it's identifier for example to "BasicCell".
3) Go to your code and use this:
FormationVC.h
#import <UIKit/UIKit.h>
#interface FormationVC : UITableViewController
#end
FormationVC.m
#import "FormationVC.h"
#interface FormationVC ()
#property (strong, nonatomic) NSArray *names;
#end
#implementation FormationVC
#pragma mark - View Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// you must not forget to call your custom init method once the view is loaded
[self setupView];
}
- (void)setupView {
// set title of VC
self.title = #"Formation View";
// create array of names
_names = #[#"John Doe", #"Lee Harvey Oswald", #"Pat Buchanan", #"Angry Orchard",
#"Sierra Nevad", #"Jeff Bridges", #"John McClain", #"Lucy Genero"];
// log number of names in names array
NSLog(#"The length of names is %lu", _names.count);
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BasicCell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%#", _names[indexPath.row]];
return cell;
}
#end
Problem IS there :-
#property (strong, nonatomic) NSArray *names;
change NSArrayTo NSMutableArray
in.h
EX:- #property (nonatomic , retain) NSMutableArray *names
and in.m
names = [[NSMutableArray alloc] init];
and then alloc init your Array and then put value its work .
I have my UITableView displaying JSON info being returned from a cloud code function. For some reason, it correctly displays the titles of the items being returned, but I can't get it to display the price as a subtitle of each cell. Setting the style as UITableViewCellStyleSubtitle doesn't seem to work, and gives me a warning stating Implicit conversion from enumeration type 'enum UITableviewCellStyle' to different enumeration type.
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// _matchCenter.dataSource = self;
// _matchCenter.delegate = self;
// [self.view addSubview:self.matchCenter];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-200);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
self.matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenterTest"
withParameters:#{
#"test": #"Hi",
}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
self.matchCenterArray = [result objectForKey:#"Top 3"];
dispatch_async(dispatch_get_main_queue(), ^{
[_matchCenter reloadData];
});
NSLog(#"Test Result: '%#'", result);
}
}];
[self.matchCenter registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.matchCenterArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *matchCenterDictionary= [self.matchCenterArray objectAtIndex:indexPath.row];
cell.textLabel.text = [matchCenterDictionary objectForKey:#"Title"];// title of the item
cell.detailTextLabel.text = [matchCenterDictionary objectForKey:#"Price"];// price of the item
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The cell you have registered is a default styled UITableViewCell, it does not have a subTitle. You can't change the style of the cell once it's created.
You basically have two options:
create a simple UITableViewCell subclass that uses UITableViewCellStyleSubtitle (or any other style of your choice)
#interface MyTableViewCell : UITableViewCell
#end
#implementation MyTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
// overwrite style
self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
return self;
}
#end
...
[self.matchCenter registerClass:[MyTableViewCell class] forCellReuseIdentifier:#"Cell"];
Or return to the old style dequeue technique where you create a cell if none could be dequeued
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
/* configure */
}
If you do this, you have to remove the registerClass:forCellReuseIdentifier: call.
I would go with option one, because most likely pretty soon you will figure out that the built in cells are very limited and you want to add your own views (e.g. labels, image views). And if you use a subclass you can use properties to access those views, and don't have to use hacks like tags to access them.
In Table View subtitle is not present otherwise you customize your cell
use detail text label
cell.detailTextLabel.text = [array objectForKey:#"Value"];
I am trying to add a simple button to a custom cell that has a web link. I added the button in story board and associated it with houseLink. Here is my view.M file where I call the button from the custom cell.
#import "IBSecondViewController.h"
#import "C21TableCell.h"
#interface IBSecondViewController ()
#end
#implementation IBSecondViewController
{
NSArray *thumbnails;
}
#synthesize data;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initialize House Array
data = [NSArray arrayWithObjects:#"2109 E Avon Cricle, Hayden Lake, ID", #"703 E Garden, Coeur d' Alene, ID", nil];
_bedroom = [NSArray arrayWithObjects:#"3", #"4", nil];
// Initialize thumbnails
thumbnails = [NSArray arrayWithObjects:#"stockHouse.png", #"stockHouse2.png", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view ddata source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"C21TableCell";
C21TableCell *cell = (C21TableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"C21TableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.addressLabel.text = [data objectAtIndex:indexPath.row];
cell.bedroomLabel.text = [_bedroom objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
NOT SURE HOW TO CALL THE BUTTON HERE
return cell;
}
-(void) buttonpressed:(UIButton *)sender {
NSString* launchUrl = #"http://apple.com/";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
#end
C21TableCell.H
#import <UIKit/UIKit.h>
#interface C21TableCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *addressLabel;
#property (nonatomic, weak) IBOutlet UILabel *bedroomLabel;
#property (nonatomic, weak) IBOutlet UIImageView *thumbnailImageView;
#property (nonatomic, weak) IBOutlet UIButton *homeLink;
#end
C21TableCell.M
#import "C21TableCell.h"
#implementation C21TableCell
#synthesize addressLabel = _nameLabel;
#synthesize bedroomLabel = _bedroomLabel;
#synthesize thumbnailImageView = _thumbnailImageView;
#synthesize homeLink = homeLink;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Just add target to button action when you create cell
[cell.homeLink addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
Please help i have been struggling passing back the data. I have 2 tableViews. 1st tableview=static table=RootVC. 2nd tableview=dynamic table=FirstVC. in RootVC i have a cell with two labels, "repeatLabel" and "repeatDetail" with a disclosure indicator. When i click on the cell it display the next table which is FirstVC, FistVC is populated with weekdays. after selection of my choice, i want the selected days to be passed back into RootVC in "repeatDetail" and when i go back still be able to see previously selected data.
My RootVC looks like this:
#import "RepeatViewController.h"
#interface SettingsViewController : UITableViewController
#property (strong, nonatomic) IBOutlet UILabel *repeatDetail;
#property (strong, nonatomic) IBOutlet UILabel *repeatLabel;
#property (strong,nonatomic) NSString *getRepeatDetail;
#property (nonatomic, strong) NSMutableArray *selectedDaysArray;
#end
in my RootVC.m
#import "SettingsViewController.h"
#interface SettingsViewController ()
#end
#implementation SettingsViewController
#synthesize repeatLabel,repeatDetail;
#synthesize getRepeatLabel;
#synthesize selectedDaysArray;
- (void)viewDidLoad
{
[super viewDidLoad];
repeatLabel.text = #"Repeat";
repeatDetail.text = getRepeatLabel;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
RepeatViewController *destinationController = segue.destinationViewController;
if( [destinationController isKindOfClass:[RepeatViewController class]] )
{
//You can reuse your selectedDays arrays
destinationController.selectedDays = self.selectedDaysArray;
[(RepeatViewController *)destinationController setCompletionBlock:^(NSArray *retDaysArray) // <- make this change
{
// Save your changes
self.selectedDaysArray = [NSMutableArray arrayWithArray: retDaysArray]; // <- make this change
NSLog(#"retDaysArray: %#", self.selectedDaysArray); //<- Add this debug line
}];
}
}
#end
My 1stVC.h
#import "SettingsViewController.h"
typedef void(^WeekdayCompletionBlock)(NSArray *retDaysArray);
#interface RepeatViewController : UITableViewController <UITableViewDataSource,UITableViewDelegate>
#property (nonatomic,strong) NSMutableArray *selectedDays;
#property (nonatomic, copy) NSArray *completionBlock;
#property (copy) WeekdayCompletionBlock returnBlock;
//#property (strong, nonatomic) IBOutlet UIBarButtonItem *saveButton;
-(IBAction)save:(id)sender;
#end
my 1stVC.m
#import "RepeatViewController.h"
#interface RepeatViewController ()
#end
#implementation RepeatViewController
#synthesize selectedDays= _selectedDays;
#synthesize completionBlock;
#synthesize returnBlock;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
completionBlock = [NSArray arrayWithObjects:#"Sunday", #"Monday", #"Tuesday", #"Wednesday", #"Thursday", #"Friday", #"Saturday", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"RepeatCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
NSString *day = completionBlock[indexPath.row];
cell.textLabel.text = day;
if ([self.selectedDays containsObject:day])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
//cell.textLabel.text = [completionBlock objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!self.selectedDays)
self.selectedDays = [[NSMutableArray alloc] init];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
//remove data from array
[self.selectedDays removeObject:[completionBlock objectAtIndex:indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//add data to array
[self.selectedDays addObject:[completionBlock objectAtIndex:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(IBAction)save:(id)sender
{
NSUserDefaults *myNewWeekString = [NSUserDefaults standardUserDefaults];
[myNewWeekString setObject:self.selectedDays forKey:#"MY_KEY_FOR_ACCESING_DAYSOFWEEK"];
[myNewWeekString synchronize];
//NSLog(#"The selected day/s is %#",self.selectedDays);
if (self.returnBlock)
{
self.returnBlock(self.selectedDays);
}
[self.navigationController popViewControllerAnimated:YES];
// NSLog(#"The selected day/s is %#",self.selectedDays);
// if (self.returnBlock)
// {
// self.returnBlock([completionBlock objectAtIndex:indexPath.row]);
//}
}
/*
-(void) setReturnBlock:(WeekdayCompletionBlock)returnBlock
{
[self.selectedDays addObject:(self.returnArray);
}
- (NSArray *)setDats
{
return [NSArray arrayWithArray:[self.selectedDays copy]];
}*/
#end
When you work with static cells you have to bind the control you are using directly, there's no need.
So what I can suggest you is the following:
Bind your controls with some specific identifier, like labelFieldRow{rowid} example: labelFieldRow1.
So on prepare for segue, just check what's the selected row and pass the data you want to the destination controller.
Probably not the best, but it should work.
You have to pass data (selected by user before) from your RootVC to FirstVC. To do that in your RootVC add property to keep the selected data;
#property (nonatomic, strong) NSMutableArray *selectedDaysArray;
In prepareForSegue method you have to pass that array to let the table view know what needs to be selected:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationController = segue.destinationViewController;
if( [destinationController isKindOfClass:[RepeatViewController class]] )
{
//You can reuse your selectedDays arrays
((RepeatViewController*)destinationController).selectedDays = self.selectedDaysArray;
[(RepeatViewController *)destinationController setReturnBlock:^(NSArray *retDaysArray) // <- make this change
{
// Save your changes
self.selectedDaysArray = [NSMutableArray arrayWithArray: retDaysArray]; // <- make this change
NSLog(#"DATA: %#", self.selectedDaysArray) //<- Add this debug line
}];
}
}
Remove this line from viewDidLoad you don't want to allocate it every time now you just pass it from rootVC
_selectedDays = [[NSMutableArray alloc] init];
And in cellForRowInIndexPath replace this line:
cell.textLabel.text = [completionBlock objectAtIndex:indexPath.row];
with this code:
NSString *day = completionBlock[indexPath.row];
cell.textLabel.text = day;
if ([self.selectedDays containsObject:day])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
And change didSelectRowAtIndexPath: to
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!self.selectedDays)
self.selectedDays = [[NSMutableArray alloc] init];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
//remove data from array
[self.selectedDays removeObject:[completionBlock objectAtIndex:indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//add data to array
[self.selectedDays addObject:[completionBlock objectAtIndex:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Hope this help.
Hi I'm trying to reload my table view based off of two different arrays. Which array should be loaded is determined by a segment control in the navigation bar. Currently it only will load the first array and nothing happens when the segment control is pressed. Below is my code any help as to why this isn't working is greatly appreciated. I've also checked that my IBAction segmenter is connected in the nib.
MessageViewController.h
#import <UIKit/UIKit.h>
#interface MessageViewController : UIViewController<UITableViewDelegate> {
IBOutlet UISegmentedControl *segmentControl;
IBOutlet UINavigationBar *navBar;
IBOutlet UITableView *tableView;
}
#property (retain, nonatomic) IBOutlet UISegmentedControl *segmentControl;
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *inbox;
#property (nonatomic, retain) NSMutableArray *sent;
#end
MessageViewController.m
#import "MessageViewController.h"
#interface MessageViewController () <UITableViewDelegate>
#end
#implementation MessageViewController
#synthesize segmentControl;
#synthesize inbox;
#synthesize sent;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.title = NSLocalizedString(#"Messages", #"Messages");
self.tabBarItem.image = [UIImage imageNamed:#"mail_2_icon&32"];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.inbox = [NSMutableArray arrayWithObjects:#"testing", #"test", #"another", nil];
self.sent = [NSMutableArray arrayWithObjects:#"test", #"another", #"testing", nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(segmentControl.selectedSegmentIndex == 0){
return [inbox count];
}else if(segmentControl.selectedSegmentIndex == 1){
return [sent count];
}else{
return [inbox count];
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(segmentControl.selectedSegmentIndex == 0){
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else if(segmentControl.selectedSegmentIndex == 1){
NSString *cellValue = [sent objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
return cell;
}
-(IBAction)segmenter{
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)dealloc {
[inbox release];
[sent release];
[segmentControl release];
[segmentControl release];
[super dealloc];
}
- (void)viewDidUnload {
[self setSegmentControl:nil];
[segmentControl release];
segmentControl = nil;
[super viewDidUnload];
}
#end
Not sure why it wasn't working in the end all I did was delete the three classes and redo everything with the code above something must have just got borked along the way but it's working now and I'm a happy camper. Didn't need the delegate stuff either since that's all done in the nib so my original code worked fine.
set the delegate and datasource methods and take breakpoint to check the data . your code is right .
tableview.delegate=self;
tableView.datasource=self;
The only problem I see is that you're using a view controller with a table view in it, but you're not setting up the delegate for it in your viewDidLoad, and you're not implementing the delegate for your view controller.
#interface MessageViewController () <UITableViewDelegate, UITableViewDataSource>
#end
In viewDidLoad:
self.tableView.delegate = self;
self.tableView.dataSource = self;
Also make sure you have everything hooked up properly in IB, both your segmented control and your table view.
EDIT: I made my own test as per what you're trying to do, Here's my own implementation file