Can NOT segue between Storyboards - ios

So I found a nice outline that gives me what I want. However, I can't switch to other storyboards?
How do I segue into other storyboards with a 'built in' window?
Included is my ViewController.M implementation file. This code seems to make a table on its own instead of use the storyboard (navigation controller)...
How do I make it work to segue to other storyboards?
#import "ViewController.h"
#interface ViewController ()
#end
#define getDataURL #"http://??.??.??.??/phpfile12.php"
#implementation ViewController
#synthesize json, storesArray, myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName : [UIColor whiteColor]};
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
//set the title
self.title = #"";
[self retrieveData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return storesArray.count;
}
- (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];
}
//cell.textLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
//Retrieve the current city object for use with this indexPath.row
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
cell.textLabel.text = currentStore.storeName;
cell.detailTextLabel.text = currentStore.storeAddress;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - UITableView Delegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController * dvc = [[DetailViewController alloc]init];
//Retrieve the current selected city
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
dvc.name = currentStore.storeName;
dvc.address = currentStore.storeAddress;
dvc.startDate = currentStore.storeStartDate;
dvc.endDate = currentStore.storeEndDate;
dvc.startTime = currentStore.storeStartTime;
dvc.endTime = currentStore.storeEndTime;
dvc.totalSales = currentStore.storeTotalSales;
dvc.voids = currentStore.storeVoids;
dvc.discounts = currentStore.storeDiscounts;
dvc.guestCount = currentStore.storeGuestCount;
dvc.peopleServed = currentStore.storePeopleServed;
dvc.employeeClockIn = currentStore.storeEmployeeClockIn;
[self.navigationController pushViewController:dvc animated:YES];
}
#pragma mark - Methods
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Set up our cities array
storesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
//Create city object
NSString * sID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString * sAddress = [[json objectAtIndex:i] objectForKey:#"storeAddress"];
NSString * sName = [[json objectAtIndex:i] objectForKey:#"storeName"];
NSString * sStartDate = [[json objectAtIndex:i] objectForKey:#"storeStartDate"];
NSString * sStartTime = [[json objectAtIndex:i] objectForKey:#"storeStartTime"];
NSString * sEndDate = [[json objectAtIndex:i] objectForKey:#"storeEndDate"];
NSString * sEndTime = [[json objectAtIndex:i] objectForKey:#"storeEndTime"];
NSString * sTotalSales = [[json objectAtIndex:i] objectForKey:#"storeTotalSales"];
NSString * sVoids = [[json objectAtIndex:i] objectForKey:#"storeVoids"];
NSString * sDiscounts = [[json objectAtIndex:i] objectForKey:#"storeDiscounts"];
NSString * sGuestCount = [[json objectAtIndex:i] objectForKey:#"storeGuestCount"];
NSString * sPeopleServed = [[json objectAtIndex:i] objectForKey:#"storePeopleServed"];
NSString * sEmployeeClockIn = [[json objectAtIndex:i] objectForKey:#"storeClockIn"];
Store * myStore = [[Store alloc]initWithStoreID: (NSString *) sID andStoreName: (NSString *) sName andStoreStartDate: (NSString *) sStartDate andStoreStartTime: (NSString *) sStartTime andStoreEndDate: (NSString *) sEndDate andStoreEndTime: (NSString *) sEndTime andStoreTotalSales: (NSString *) sTotalSales andStoreVoids: (NSString *) sVoids andStoreDiscounts: (NSString *) sDiscounts andStoreGuestCount: (NSString *) sGuestCount andStorePeopleServed: (NSString *) sPeopleServed andStoreEmployeeClockIn: (NSString *) sEmployeeClockIn andStoreAddress: (NSString *) sAddress];
//Add our city object to our cities array
[storesArray addObject:myStore];
}
[self.myTableView reloadData];
}
#end

To instantiate a view controller from another storyboard you can use UIStoryboard storyboardWithName
UIViewController *dvc = [[UIStoryboard storyboardWithName:#"yourStoryboardName" bundle:nil] instantiateViewControllerWithIdentifier:#"yourViewIdentifier"];
[self.navigationController pushViewController:dvc animated:YES];
This is more a general answer, though.

I don't understand what you exactly asking but for simple segue i used this line of code
[self performSegueWithIdentifier:#"identifier" sender:self];
if you want to segue without linking than you have to give identifier to view controller and use this code below
UIViewController *homeViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"identifier"];
[self presentViewController:homeViewController animated:0 completion:nil];

I am not entire sure what you mean by "Segue to other storyboard"? The following code allows you to jump to a totally different view controller tree inside the same storyboard by a click of button or other action.
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *initViewController = [storyboard instantiateViewControllerWithIdentifier:#"SecondScreen"];
delegate.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
delegate.window.rootViewController = initViewController;
[delegate.window makeKeyAndVisible];
Main is the name of your storyboard that you want to jump into.
SecondScreen is the storyboard ID of the view controller. Most likely it is a navigation or a container. You will need to set "SecondScreen" under identity inspector.

Related

Store address book of iOS in array and display that in UITableView

I want to store address book of iOS in array and display that in UITableView. This is the code I am using. I just want contact name and phone number to be displayed.
pragma mark- address book methods
(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
ABPeoplePickerNavigationController *picker= [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];
return NO;
}
(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
ABMultiValueRef phone = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonPhoneProperty);
ABMultiValueRef personID = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef phoneID = ABMultiValueCopyValueAtIndex(phone, 0);
//CFStringRef personName= ABMultiValueCopyValueAtIndex(personID, 0);
NSLog(#"%#",[NSString stringWithFormat:#"%#", phoneID]);
NSLog(#"%#",[NSString stringWithFormat:#"%#", personID]);
}
Please refer to Rays addressbook tutorial. I think it should answer all your questions.
Why are u calling the picker navigator on beginning of a text? You should call it through a button added as a right bar button item. Then select the persons you want and store them in a mutable array. After that dismiss the controller and load the table view.
Edited:
Please find the code below for your reference. I hope it might help in understanding how it is working. Here is the reference link to the sample code as well.
Interface:
#import <UIKit/UIKit.h>
#interface JSViewController : UITableViewController
#end
Implementation:
#import "JSViewController.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#interface JSViewController ()<ABPeoplePickerNavigationControllerDelegate,UITableViewDataSource,UITableViewDelegate>
#property (nonatomic, strong) NSMutableArray *peopleSelected;
#end
#implementation JSViewController
-(NSMutableArray *)peopleSelected
{
if (!_peopleSelected) {
_peopleSelected = [NSMutableArray new];
}
return _peopleSelected;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIBarButtonItem *selectPerson = [[UIBarButtonItem alloc] initWithTitle:#"Select" style:UIBarButtonItemStyleBordered target:self action:#selector(btnSelectHandler:)];
self.navigationItem.rightBarButtonItem = selectPerson;
}
- (void)btnSelectHandler:(id)sender
{
ABPeoplePickerNavigationController *peoplePicker = [ABPeoplePickerNavigationController new];
peoplePicker.peoplePickerDelegate = self;
[self.navigationController presentViewController:peoplePicker animated:YES completion:^{
}];
}
#pragma mark - ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
[self dismissViewControllerAnimated:YES completion:^{
if (self.peopleSelected) {
[self.tableView reloadData];
}
}];
}
The below method is deprecated in iOS 8.0. You can use the function
- peoplePickerNavigationController:didSelectPerson:
instead of this:
//Deprecated in iOS 8.0.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
NSString *name = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
ABMultiValueRef phoneNumbers = (ABRecordCopyValue(person, kABPersonPhoneProperty));
NSString *mobile = #"";
NSString *label = #"";
for (CFIndex i=0 ; i<ABMultiValueGetCount(phoneNumbers); i++) {
label = (__bridge NSString *)ABMultiValueCopyLabelAtIndex(phoneNumbers, i);
if ([label isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) {
mobile = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
}else if([label isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel]){
mobile = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
break;
}
}
NSDictionary *dict = #{#"name":name,
#"phone":mobile};
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.phone == %# && self.name == %#",mobile,name];
NSArray *personAlready = [self.peopleSelected filteredArrayUsingPredicate:predicate];
NSLog(#"personAlready %#",personAlready);
if (!personAlready.count) {
[self.peopleSelected addObject:dict];
}
return NO;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.peopleSelected.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSDictionary *dict = self.peopleSelected[indexPath.row];
cell.textLabel.text = dict[#"name"];
return cell;
}
#pragma mark - UITableViewDelegate
#end

Segue not updated inside TableViewController

Good afternoon,
I have created a Segue in my TableViewController where the user can touch the user profile and it sends that username to a ProfileViewController, where the user information is loaded (posts, image, info...) (something like a Facebook wall).
The problem is when I touch one user, it displays everything correctly, but when I touch another profile image, it displays the same ProfileViewController again, like the username is not updated and it's send wrong.
When I touch anywhere on the screen and then I touch again the user profile, in that case it works, but I need to make this work in every case.
I'm going to post my TableViewController if that helps you to find the problem because it's almost working, the only thing that I need to fix is that username that is not updated (Tap Gesture Recognizer over the image).
The segues are at the end of the code.
TableViewController.m
//
// CarTableViewController.m
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import "OtherProfileUserViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
//self.refreshControl.backgroundColor = [UIColor blackColor];
//self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (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 [_jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"imagen"] options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
-(void)fetchJson {
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
NSLog(#"carModels ==> %#", _jsonArray);
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
if ([segue.identifier isEqualToString:#"segueprofile2"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
}
#end
Thanks in advance.
OK, here is one of the options.
1. Delete all existing segues (segueprofile and segueprofile2)
2. Connect your tableviewcontroller (important: not tableview but controller itself) with your details controller by push-segue and name it segueprofile3
3. Refactor your code in the following manner
#property (nonatomic, strong) NSIndexPath * selectedIndexPath;
...
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)anIndexPath {
self.selectedIndexPath = anIndexPath;
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile3"]) {
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:selectedIndexPath.row] valueForKey:#"username"];
}
}
Another option. Place UIButton control right over avatar UIImageView. Create associated IBOutlet inside your CarTableViewCell class and make outlet connection.
#property (nonatomic, weak) UIButton * btnAvatar;
Next, modify CarTableViewController code
//1. declare new propery
#property (nonatomic, strong) id selectedProfile;
//2. implement future button tap handler
-(IBAction) btnAvatarDidPress:(id) sender {
int tag = ((UIButton *) sender).tag;
self.selectedProfile = [_jsonArray objectAtIndex:tag];
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
//Extend your cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.btnAvatar.tag = indexPath.row;
... rest of method
}
then remove didSelectRowAtIndexPath method, and connect btnAvatar Touch Up Inside action to btnAvatarDidPress method inside your controller code.
That's all I hope I've forgot nothing.
here is your example, in prepareForSegue, get the cell which button is in:
id v = sender;
while (![(v= v.superView) isKindOfClass:[UITableViewCell class]]
&& v!=nil) ;
if (v==nil)
// no ancestor view is cell.
else{
// now v is the cell.
NSIndexPath * indexPath = [self.tableView indexPathForCell:v];
// do the left
}

TableView in iOS Settings Bundle

I am a newbie on iOS Development and I am sorting out how am I going to have a table view with a checkmark on the settings bundle like this:
Is there any way to do it? Or is this just only available for specific iOS approved apps?
Looking forward for an answer. Thanks.
You can achieve this through Multi Value Element. When the user taps a preference containing a multi-value element, the Settings application displays a new page with the possible values to choose from. Google it for the tutorials if needed (Multivalue option for the settings bundle).
Here are the details : PSMultiValueSpecifier
If I am guessing right and you want to know how to display settings outside your app and in the iOS Settings, then check out this tutorial. It should get you started.
Taken out of the link below:
I have been searching around and couldn't find a boilerplate solution so created my own code for doing this. It supports the setting types Title, Group, Text Field, Multi Value and Toggle Switch.
It does NOT SUPPORT Slider.
This solution does support portrait AND landscape mode and can also handle changing over device orientations.
First off all I'm assuming that you are using the following code to read out your default values from the Settings.bundle.
- (void) registerDefaultsFromSettingsBundle
{
NSLog(#"Registering default values from Settings.bundle");
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
[defs synchronize];
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource: #"Settings" ofType: #"bundle"];
if(!settingsBundle)
{
NSLog(#"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent: #"Root.plist"]];
NSArray *preferences = [settings objectForKey: #"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for (NSDictionary *prefSpecification in preferences)
{
NSString *key = [prefSpecification objectForKey:#"Key"];
if (key)
{
// check if value readable in userDefaults
id currentObject = [defs objectForKey: key];
if (currentObject == nil)
{
// not readable: set value from Settings.bundle
id objectToSet = [prefSpecification objectForKey: #"DefaultValue"];
[defaultsToRegister setObject: objectToSet forKey: key];
NSLog(#"Setting object %# for key %#", objectToSet, key);
}
else
{
// already readable: don't touch
NSLog(#"Key %# is readable (value: %#), nothing written to defaults.", key, currentObject);
}
}
}
[defs registerDefaults: defaultsToRegister];
[defs synchronize];
}
Okay now you'll need 2 classes. SettingsTableViewController and MultiValueTableViewController.
SettingsTableViewController.h
//
// SettingsTableViewController.h
// Cochlear App
//
// Created by Gilles Lesire on 16/07/14.
// Free to use
//
#import <UIKit/UIKit.h>
#import "MultiValueTableViewController.h"
#interface SettingsTableViewController : UITableViewController <MultiValueDelegate> {
NSMutableArray *labelViews;
NSMutableArray *textViews;
NSMutableArray *settingsKeys;
NSMutableArray *settingsTableSections;
NSMutableArray *settingsTableData;
}
#end
SettingsTableViewController.m
//
// SettingsTableViewController.m
// Cochlear App
//
// Created by Gilles Lesire on 16/07/14.
// Free to use
////
#import "SettingsTableViewController.h"
#define labelCGRectX 25
#define labelCGRectY 25
#define labelCGRectWidth 140
#define labelCGRectHeight 21
#define typeGroup #"PSGroupSpecifier"
#define typeTitle #"PSTitleValueSpecifier"
#define typeToggleSwitch #"PSToggleSwitchSpecifier"
#define typeMultiValue #"PSMultiValueSpecifier"
#define typeTextField #"PSTextFieldSpecifier"
#interface SettingsTableViewController ()
#end
#implementation SettingsTableViewController
- (id)initWithStyle: (UITableViewStyle)style
{
self = [super initWithStyle: style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Track rotation changes
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(deviceOrientationDidChange) name: UIDeviceOrientationDidChangeNotification object: nil];
// Avoid tab bar to overlap tableview
self.edgesForExtendedLayout = UIRectEdgeAll;
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, CGRectGetHeight(self.tabBarController.tabBar.frame), 0.0f);
// Custom initialization
labelViews = [NSMutableArray arrayWithObjects: nil];
textViews = [NSMutableArray arrayWithObjects: nil];
settingsTableSections = [NSMutableArray arrayWithObjects: nil];
settingsTableData = [NSMutableArray arrayWithObjects: nil];
settingsKeys = [NSMutableArray arrayWithObjects: nil];
NSLog(#"Created arrays");
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource: #"Settings" ofType: #"bundle"];
if(!settingsBundle) {
NSLog(#"Could not find Settings.bundle");
} else {
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent: #"Root.plist"]];
NSArray *preferences = [settings objectForKey: #"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity: [preferences count]];
for (NSDictionary *prefSpecification in preferences) {
NSLog(#"%#", prefSpecification);
NSString *title = [prefSpecification objectForKey: #"Title"];
NSString *type = [prefSpecification objectForKey: #"Type"];
if([type isEqualToString: typeGroup]) {
// Create new section
[settingsTableSections addObject: title];
NSMutableArray *newSection = [NSMutableArray arrayWithObjects: nil];
[settingsTableData addObject: newSection];
} else {
// Add specification to last section
[[settingsTableData objectAtIndex: ([settingsTableData count] - 1)] addObject:prefSpecification];
}
}
}
}
- (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 [settingsTableSections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[settingsTableData objectAtIndex: section] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [settingsTableSections objectAtIndex: section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Get the dictionary item
NSDictionary *prefSpecification = [[settingsTableData objectAtIndex: indexPath.section] objectAtIndex: indexPath.row];
NSString *title = [prefSpecification objectForKey: #"Title"];
NSString *key = [prefSpecification objectForKey: #"Key"];
NSString *type = [prefSpecification objectForKey: #"Type"];
// Define cell
UITableViewCell *cell;
// Keep tag of keys
[settingsKeys addObject: key];
int tag = [settingsKeys count] - 1;
if([type isEqualToString: typeTitle]) {
// Create cell
cell = [tableView dequeueReusableCellWithIdentifier: #"Cell" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Set title
cell.textLabel.text = title;
// Add label
UILabel *labelView = [[UILabel alloc] initWithFrame: CGRectMake(labelCGRectX, labelCGRectY, labelCGRectWidth, labelCGRectHeight)];
labelView.text = [[NSUserDefaults standardUserDefaults] objectForKey: key];
labelView.textAlignment = NSTextAlignmentRight;
labelView.textColor = [UIColor grayColor];
cell.accessoryView = labelView;
}
if([type isEqualToString: typeToggleSwitch]) {
// Create cell
cell = [tableView dequeueReusableCellWithIdentifier: #"Cell" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Set title
cell.textLabel.text = title;
// Add switch
UISwitch *switchView = [[UISwitch alloc] initWithFrame: CGRectZero];
cell.accessoryView = switchView;
switchView.tag = tag;
[switchView setOn: [[[NSUserDefaults standardUserDefaults] objectForKey: key] boolValue] animated: NO];
// Connect action to switch
[switchView addTarget: self action: #selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
}
if([type isEqualToString: typeTextField]) {
// Create cell
cell = [tableView dequeueReusableCellWithIdentifier: #"Cell" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int frameSize = self.view.frame.size.width;
UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(15, 10, frameSize,labelCGRectHeight)];
textField.tag = tag;
textField.text = [[NSUserDefaults standardUserDefaults] objectForKey: key];
[textField addTarget: self
action: #selector(textFieldChanged:)
forControlEvents: UIControlEventEditingChanged];
[cell.contentView addSubview: textField];
// Tract text field
[textViews addObject: textField];
}
if([type isEqualToString: typeMultiValue]) {
// Create cell
cell = [tableView dequeueReusableCellWithIdentifier: #"MultiValueCell" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Get value
int value = [[[NSUserDefaults standardUserDefaults] objectForKey: key] intValue];
NSArray *values = [prefSpecification objectForKey: #"Values"];
NSArray *titles = [prefSpecification objectForKey: #"Titles"];
NSString *multiValue = #"Unknown";
int index = [values indexOfObject: [NSString stringWithFormat: #"%d", value]];
if(index >= 0 && index < [values count]) {
multiValue = [titles objectAtIndex: index];
}
// Set title
cell.textLabel.text = title;
int frameSize = self.view.frame.size.width;
// Add label
UILabel *labelView = [[UILabel alloc] initWithFrame: CGRectMake((frameSize - labelCGRectWidth - 30), 12, labelCGRectWidth, labelCGRectHeight)];
labelView.textAlignment = NSTextAlignmentRight;
labelView.text = multiValue;
labelView.textColor = [UIColor grayColor];
[cell addSubview: labelView];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Track label
[labelViews addObject: labelView];
}
return cell;
}
- (void) switchChanged: (id) sender {
UISwitch* switchControl = sender;
NSString *key = [settingsKeys objectAtIndex: switchControl.tag];
NSNumber *numberValue = [NSNumber numberWithBool: switchControl.on];
[[NSUserDefaults standardUserDefaults] setObject: numberValue forKey: key];
}
- (void) textFieldChanged: (id) sender {
UITextField* textControl = sender;
NSString *key = [settingsKeys objectAtIndex: textControl.tag];
NSString *stringValue = textControl.text;
[[NSUserDefaults standardUserDefaults] setObject: stringValue forKey: key];
}
- (void) selectedMultiValue {
[self reloadTable];
}
- (void) deviceOrientationDidChange {
[self reloadTable];
}
- (void)prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
if ([[segue identifier] isEqualToString: #"changeMultiValue"])
{
MultiValueTableViewController *multiValueViewController =
[segue destinationViewController];
NSIndexPath *indexPath = [self.tableView
indexPathForSelectedRow];
// Get the dictionary item
NSDictionary *prefSpecification = [[settingsTableData objectAtIndex: indexPath.section] objectAtIndex: indexPath.row];
multiValueViewController.prefSpecification = prefSpecification;
multiValueViewController.delegate = self;
}
}
- (void) reloadTable {
for (UILabel *labelView in labelViews) {
[labelView removeFromSuperview];
}
for (UITextField *textView in textViews) {
[textView removeFromSuperview];
}
// Remove references to objects for garbage collection
labelViews = [NSMutableArray arrayWithObjects: nil];
textViews = [NSMutableArray arrayWithObjects: nil];
[self.tableView reloadData];
}
- (void) dealloc {
// Remove observers
[[NSNotificationCenter defaultCenter] removeObserver: self];
}
#end
MultiValueTableViewController.h
//
// MultiValueTableViewController.h
// Cochlear App
//
// Created by Gilles Lesire on 16/07/14.
// Free to use
//
#import <UIKit/UIKit.h>
#import "SettingsController.h"
#protocol MultiValueDelegate
- (void) selectedMultiValue;
#end
#interface MultiValueTableViewController : UITableViewController {
NSDictionary *prefSpecification;
}
#property (nonatomic) id<MultiValueDelegate> delegate;
#property (strong, nonatomic) NSDictionary *prefSpecification;
#end
MultiValueTableViewController.m
//
// MultiValueTableViewController.m
// Cochlear App
//
// Created by Gilles Lesire on 16/07/14.
// Free to use
//
#import "MultiValueTableViewController.h"
#interface MultiValueTableViewController ()
#end
#implementation MultiValueTableViewController
#synthesize prefSpecification;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *title = [prefSpecification objectForKey: #"Title"];
self.navigationItem.title = title;
// Avoid tab bar to overlap tableview
self.edgesForExtendedLayout = UIRectEdgeAll;
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, CGRectGetHeight(self.tabBarController.tabBar.frame), 0.0f);
}
- (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
{
NSArray *values = [prefSpecification objectForKey: #"Values"];
// Return the number of rows in the section.
return [values count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: #"Cell" forIndexPath:indexPath];
NSString *key = [prefSpecification objectForKey: #"Key"];
NSArray *titles = [prefSpecification objectForKey: #"Titles"];
NSArray *values = [prefSpecification objectForKey: #"Values"];
NSString *title = [titles objectAtIndex: indexPath.row];
// Create cell
cell.selectionStyle = UITableViewCellSelectionStyleGray;
// Set title
cell.textLabel.text = title;
// If this is the selected value
if([[values objectAtIndex: indexPath.row] intValue] == [[[NSUserDefaults standardUserDefaults] objectForKey: key] intValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [prefSpecification objectForKey: #"Key"];
NSArray *values = [prefSpecification objectForKey: #"Values"];
NSNumber *value = [values objectAtIndex: indexPath.row];
[[NSUserDefaults standardUserDefaults] setObject: value forKey: key];
[self.delegate selectedMultiValue];
[self.tableView reloadData];
}
#end
Storyboard Now go the storyboard and create a TableViewController. Select the TableViewController and Choose "Editor" -> "Embed in" -> "Navigation controller".
Set the class of the TableViewController as SettingsTableViewController. Set the identifier of the cell as "Cell", add a second TableViewCell to the TableView and set it's identifier as "MultiValueCell". Add a second TableViewController, and CTRL+CLICK and drag from the MultiValueCell to the second TableViewController. Set the class of the second TableViewController as MultiValueTableViewController. Set the identifier of the cell in the second TableViewController as "Cell" too. That's it!
#import "SettingViewController.h"
NSInteger selectedIndex;
//Use this, it works for me
- (void)viewDidLoad
{
selectedIndex = 0;
[super viewDidLoad];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50.0f;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_arrayForSaveSetting count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (indexPath.row==selectedIndex) {
cell.accessoryType =UITableViewCellAccessoryCheckmark;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedIndex=indexPath.row;
[_tblSaveSetting reloadData];
}

define the UITableViewCell out of Storyboard with NIB

I used the Json array to show data from server.
when I change the CellIdentifier to #Cell which i used in CellIdentifier the pushDetailView is working and it's going to next page but when I change to CustomCell again just show the name of city and state in first page and when i click on that doesnt go to next page. the reason I need the #CustomCell because I need 2 labels view in first page and when I change it to #cell it just show one label.
Thank you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
City * cityObject;
cityObject = [ citiesArry objectAtIndex:indexPath.row];
cell.textLabel.text = cityObject.cityState;
cell.detailTextLabel.text = cityObject.cityPopulation;
cell.detailTextLabel.numberOfLines = 4;
//NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://mobileapps.binaryappdev.com/applelogo.png"] ];
//[[cell imageView] setImage:[UIImage imageWithData:imageData] ];
return cell;
}
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"pushDetailView"])
{
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
City * object = [citiesArry objectAtIndex: indexPath.row];
[[segue destinationViewController] getCity:object];
}
}
#pragma mark -
#pragma mark Class Methods
-(void) retrievedData;
{
NSURL * URL = [ NSURL URLWithString:getDataURL];
NSData * data = [ NSData dataWithContentsOfURL:URL];
jsonArry = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//city
citiesArry = [[NSMutableArray alloc] init];
//loop
for (int i=0; i<jsonArry.count; i++) {
NSString * cID = [[ jsonArry objectAtIndex:i] objectForKey:#"id"];
NSString * cName = [[ jsonArry objectAtIndex:i] objectForKey:#"cityName"];
NSString * cState = [[ jsonArry objectAtIndex:i] objectForKey:#"cityState"];
NSString * cCountry = [[ jsonArry objectAtIndex:i] objectForKey:#"country"];
NSString * cPopulation = [[ jsonArry objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString * cImage = [[ jsonArry objectAtIndex:i] objectForKey:#"cityImage"];
[citiesArry addObject:[[City alloc] initWithcityName:cName andcityState:cState andcityCountry:cCountry andcityPopulation:cPopulation andcityImage:cImage andcityID:cID ]];
}
[self.tableView reloadData];
}
#end
DetailViewController
#synthesize cityNameLabel, stateLabel, countryLabel, populationLabel, currentCity;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setLabels];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark Class Methods
-(void) getCity:(id)cityObject
{
currentCity = cityObject;
}
-(void) setLabels
{
cityNameLabel.text= currentCity.cityName;
countryLabel.text = currentCity.cityCountry;
stateLabel.text = currentCity.cityState;
populationLabel.text = currentCity.cityPopulation;
cityNameLabel.numberOfLines= 0;
}
#end
if you don´t have segue for your customcell when you push in a cell your method didSelectRow:AtIndexPath will be called. You can do yourself a pushViewController from that method or [self performSegueWithIdentifier: #"pushDetailView" sender: self];

TableView does not reloaddata when I clicked "More data..." at the last row of tableView

Request my test webService for the data,
The tableView's last row is "More data..."
when click this row, send another request to get more data,
and I use [tableView reloaddata] many times, but there is nothing
happened, and I dont know why.So,please help me with this problem.
Thank you in advance.
and there is my tableViewController.h class:
#import <UIKit/UIKit.h>
#import "NoticeDetailViewController.h"
#interface NoticeViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *allNoticeArray;
NSArray *addNoticeArray;
NSInteger totalNotice;
NSInteger pageIndex;
UITableView *tableView;
}
#property (nonatomic, retain) NSMutableArray *allNoticeArray;
#property (nonatomic, retain) NSArray *addNoticeArray;
#property NSInteger totalNotice;
#property NSInteger pageIndex;
#property (nonatomic, retain) UITableView *tableView;
- (NSMutableArray *)getNoticeList :(NSInteger)pageIndex;
#end
And tableViewController.m class:
#import "NoticeViewController.h"
#import "Notice.h"
#import "OAURLEncodingAdditions.h"
#interface NoticeViewController ()
#end
#implementation NoticeViewController
#synthesize allNoticeArray;
#synthesize addNoticeArray;
#synthesize pageIndex;
#synthesize tableView;
#synthesize totalNotice;
- (NSMutableArray *)getNoticeList :(NSInteger)pageIndex
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *userId = appDelegate.user.userId;
NSString *departmentId = appDelegate.user.departmentId;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetAnnouncement?userId=%#&departmentId=%#&pageIndex=%d&pageSize=%d",userId,departmentId,self.pageIndex,1]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
[request startSynchronous];
NSError *error = [request error];
if (!error)
{
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSArray *noticeArray = [responseDict objectForKey:#"d"];
NSMutableArray *arrayOfAllNotice = [[NSMutableArray alloc] init];
for (NSDictionary *noticeDic in noticeArray)
{
NSString *body = [noticeDic objectForKey:#"Body"];
NSString *departmentName = [noticeDic objectForKey:#"DepartmentName"];
NSString *noticeId = [noticeDic objectForKey:#"Id"];
NSString *isTop = [noticeDic objectForKey:#"IsTop"];
NSString *readState = [noticeDic objectForKey:#"ReadState"];
NSString *realName = [noticeDic objectForKey:#"RealName"];
NSString *title = [noticeDic objectForKey:#"Title"];
int noid = [noticeId intValue];
int isto = [isTop intValue];
int read = [readState intValue];
Notice *notice = [[Notice alloc] initWithBody:body
departmentName:departmentName
noticeId: noid
isTop:isto
readState:read
realName:realName
title:title];
[arrayOfAllNotice addObject:notice];
}
self.addNoticeArray = [[NSArray alloc] initWithArray:arrayOfAllNotice];
}
else
{
....
}
[allNoticeArray addObjectsFromArray:addNoticeArray];
NSLog(#"allNoticeArray count: %d",[allNoticeArray count]); //Here:When the last row clicked, the number changes:1->2
[self.tableView reloadData];
return allNoticeArray;
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger theNumberOfRowsInSection;
if ( [allNoticeArray count] < (self.totalNotice))
{
theNumberOfRowsInSection = [allNoticeArray count]+1;
}
if ( [allNoticeArray count] == (self.totalNotice))
{
theNumberOfRowsInSection = [allNoticeArray count];
}
return theNumberOfRowsInSection;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView reloadData];
static NSString *NoticeListTableIdentifier = #"NoticeListTableIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:NoticeListTableIdentifier];
if ( cell == nil )
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NoticeListTableIdentifier] autorelease];
}
if ( [allNoticeArray count] < (self.totalNotice) )
{
if ( [indexPath row] != [allNoticeArray count])
{
NSUInteger row = [indexPath row];
Notice *noticeOfTheRow = [allNoticeArray objectAtIndex:row];
NSString *title = noticeOfTheRow.title;
cell.textLabel.text = title;
}
else
{
cell.textLabel.text = #"More...";
}
}
if ( [allNoticeArray count] == (self.totalNotice) )
{
NSUInteger row = [indexPath row];
Notice *noticeOfTheRow = [allNoticeArray objectAtIndex:row];
NSString *title = noticeOfTheRow.title;
cell.textLabel.text = title;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( [indexPath row] != [allNoticeArray count])
{
NSUInteger row = [indexPath row];
Notice *notice = [allNoticeArray objectAtIndex:row];
NSString *noticeDetailTitle = notice.title;
NoticeDetailViewController *noticeDetailViewController = [[[NoticeDetailViewController alloc] init] autorelease];
noticeDetailViewController.title = noticeDetailTitle;
ticeDetailViewController.noticeIdForGet = notice.noticeId;
[self.navigationController pushViewController:noticeDetailViewController animated:YES];
}
if ( [indexPath row] == [allNoticeArray count])
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"reload...";
self.pageIndex ++;
[self getNoticeList:self.pageIndex];
[self.tableView reloadData];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
- (void)pushBack
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.allNoticeArray = [[NSMutableArray alloc] init];
self.pageIndex = 1;
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"reload...";
self.title = #"Notice";
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:#"back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(pushBack)];
self.navigationItem.leftBarButtonItem = leftButton;
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:#"reload"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(reloadNotice)];
self.navigationItem.rightBarButtonItem = rightButton;
self.allNoticeArray = [self getNoticeList:self.pageIndex];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
#end
change:
if ( [indexPath row] == [allNoticeArray count])
to:
if ( [indexPath row] == [allNoticeArray count]-1)
The reason is that array (and row) indexing are base 0. So if an array has, say 3 objects, last object's index is 2
BTW,with the new language features, there's no need to declare the ivars in the interface. The compiler will take care of them if you have already declared the properties and synthesized them.
#interface NoticeViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *allNoticeArray;
NSArray *addNoticeArray;
NSInteger totalNotice;
NSInteger pageIndex;
UITableView *tableView;
}
//...
#end

Resources