UIActivityIndicatorView Not Appearing - ios

I am trying to show a UIActivityIndicatorView while my table view is loading data and have it disappear once loading is finished. The loading indicator never appears. What am I doing wrong?
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: #"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"]
#import "BBYoutubeVideosTableViewController.h"
#import "Reachability.h"
#import "TSMessage.h"
#import "TSMessageView.h"
#import "YoutubeCell.h"
#import "KFBYoutubeVideoView.h"
#import "KFBAppDelegate.h"
#interface BBYoutubeVideosTableViewController ()
{
UIActivityIndicatorView *loadingIndicator;
}
#end
#implementation BBYoutubeVideosTableViewController
#synthesize title, videoID, thumbURL, descriptionString, url, titleArray, videoIDArray, thumbArray, descriptionArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
UIImageView *backgroundImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"plain_app-background.png"]];
CGFloat width = [[UIScreen mainScreen]bounds].size.width;
CGFloat height = [[UIScreen mainScreen]bounds].size.height;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
}
else
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(142, 365, 37, 37)];
}
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
loadingIndicator.hidesWhenStopped = YES;
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if(networkStatus == NotReachable)
{
[TSMessage showNotificationWithTitle:#"Network Error" subtitle:#"No active network connection!" type:TSMessageNotificationTypeError];
[loadingIndicator stopAnimating];
}
else {
[self.tableView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
}
self.title = #"Bluegrass & Backroads";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.tableView.backgroundView = backgroundImage;
url = [NSURL URLWithString:#"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
if (data == nil)
{
NSLog(#"data is nil");
}
else
{
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
}
});
}
- (void)viewDidDisappear:(BOOL)animated
{
[loadingIndicator stopAnimating];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
titleArray = [[NSMutableArray alloc]init];
videoIDArray = [[NSMutableArray alloc]init];
thumbArray = [[NSMutableArray alloc]init];
descriptionArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *items = [json objectForKey:#"items"];
for (NSDictionary *item in items)
{
NSDictionary *snippet = [item objectForKey:#"snippet"];
title = [snippet objectForKey:#"title"];
videoID = [[snippet objectForKey:#"resourceId"] objectForKey:#"videoId"];
thumbURL = [[[snippet objectForKey:#"thumbnails"] objectForKey:#"default"] objectForKey:#"url"];
descriptionString = [snippet objectForKey:#"description"];
[titleArray addObject:title];
[videoIDArray addObject:videoID];
UIImage *thumbnailImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbURL]]];
[thumbArray addObject:thumbnailImage];
[descriptionArray addObject:descriptionString];
}
[self.tableView reloadData];
[loadingIndicator stopAnimating];
}
- (IBAction)morePressed:(id)sender
{
NSURL *kyfbVideos = [NSURL URLWithString:#"https://www.youtube.com/playlist?list=PL9DC706DCCCE00188"];
[[UIApplication sharedApplication] openURL:kyfbVideos];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [titleArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 215;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
footerView.backgroundColor = [UIColor clearColor];
CGFloat width = footerView.frame.size.width;
UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
moreButton.backgroundColor = [UIColor clearColor];
[moreButton setTitle:#"More" forState:UIControlStateNormal];
[moreButton setTitleColor:kfbBlue forState:UIControlStateNormal];
moreButton.titleLabel.textAlignment = NSTextAlignmentCenter;
moreButton.titleLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:25.0];
moreButton.frame = CGRectMake(width / 2 - 25, 0, 50, 50);
moreButton.layer.cornerRadius = 25.0;
moreButton.layer.borderWidth = 2.0f;
moreButton.layer.borderColor = kfbBlue.CGColor;
moreButton.clipsToBounds = YES;
moreButton.backgroundColor = [UIColor clearColor];
[moreButton addTarget:self action:#selector(morePressed:) forControlEvents:UIControlEventTouchUpInside];
[footerView addSubview:moreButton];
return footerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
YoutubeCell *cell = [tableView dequeueReusableCellWithIdentifier:#"youtubeCell"];
if (!cell)
{
NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:#"YoutubeCell" owner:self options:NULL];
cell = [nibs firstObject];
}
cell.videoTitle.text = [titleArray objectAtIndex:indexPath.row];
cell.videoDescription.text = [descriptionArray objectAtIndex:indexPath.row];
cell.videoThumbnail.image = [thumbArray objectAtIndex:indexPath.row];
cell.videoTitle.textColor = kfbBlue;
cell.videoDescription.textColor = kfbBlue;
cell.videoTitle.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:22.0];
cell.videoDescription.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:16.0];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]init];
videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:videoView animated:YES];
}
else
{
KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]initWithNibName:nil bundle:nil];
videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
NSMutableArray *details = [self.splitViewController.viewControllers mutableCopy];
UINavigationController *detailNav = [[UINavigationController alloc]initWithRootViewController:videoView];
[details replaceObjectAtIndex:1 withObject:detailNav];
KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
appDelegate.splitViewController.viewControllers = details;
appDelegate.window.rootViewController = self.splitViewController;
appDelegate.splitViewController.delegate = videoView;
[appDelegate.splitViewController viewWillAppear:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

I figured it out. tableView was being initialized after adding loadingIndicator as a subview.

Related

UICollectionViewFlowLayout position

I have a problem
When I click the tabcontoller uıcollectionviewflowlayout position is changing :(
The following code does not work
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.myCollectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
}
before image:
When I click the tabcontoller
after image:
please help me
other image upload
updated:
Remove
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.myCollectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
from viewWillAppear and put it back in viewDidLoad.
- (void)viewDidLoad
{
[self.myCollectionView registerNib:[UINib nibWithNibName:PhotoCellIdentifier bundle:[NSBundle mainBundle]]
forCellWithReuseIdentifier:PhotoCellIdentifier];
self.myCollectionView.delegate=self;
self.myCollectionView.dataSource=self;
[self.myCollectionView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
[self yukle];
}
-(void) storkontrol:(NSArray*)skulist{
[[RMStore defaultStore] requestProducts:[NSSet setWithArray:skulist] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
if (products.count ==0)
{
self.eserList = nil;
[self sitedeveriyokbilgi];
} else
{
NSMutableArray *ll = [[NSMutableArray alloc] init];
int i =0;
// satın alışverişte alınan ürünelr geliyor
// NSLog(#"RMStore dan ürünler bekleniyor..");
for (SKProduct*urun in products) {
// NSLog(#"ürün : %#",urun.productIdentifier);
for (EserFiles*eser in self.eserList) {
if ([urun.productIdentifier isEqualToString:eser.eser.eserstokkod])
{
eser.eser.product = urun;
[ll insertObject:eser atIndex:i];
i++;
}
}
}
// NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"eser.esersayi" ascending:NO selector:#selector(compare:)];
// [ll sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
self.eserList = ll;
// [HesapViewController setEserListVitrin: ll];
// [AyarlarViewController setEserListVitrin: ll];
[global setEserListVitrin: ll];
// NSLog(#"RMStore dan ürün çekme işlemi bitti");
[self.myCollectionView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
_productsRequestFinished = YES;
[spinnerorta stopAnimating];
}
} failure:^(NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[spinnerorta stopAnimating];
NSLog(#"failure:^(NSError *error urunlist %#",error.localizedDescription);
}];
}
-(void)sitedeveriyokbilgi{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 270)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor grayColor];
label.numberOfLines = 0;
label.text = #"Listelenecek eser bulunamadı";
[self.view addSubview:label];
NSLog(#"Listelenecek eser bulunamadı");
[spinnerorta stopAnimating];
}
-(void)yukle{
spinnerorta = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinnerorta.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
spinnerorta.center = self.view.center;
[spinnerorta startAnimating];
[self.view addSubview: spinnerorta];
//eğer kategoriden geliyorsa hiç bir zamanön bellekleme olmayacak
__block NSArray *arry ;
NSMutableArray *skulist = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//ana sayfa ise
if (self.gelenviewid==1)
{
if ([[global getEserList] count] ==0 )
{
// NSLog(#"yeni liste alınıyor.......");
NSMutableArray *skulist = [[NSMutableArray alloc] init];
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
arry = [jsonLoader locationsFromJSONFile];
} else{
self.eserList =[global getEserList];
// NSLog(#"ön bellekten doldu....");
[self.myCollectionView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
// [spinnerorta stopAnimating];
return ;
}
} else if(self.gelenviewid==2)
{
arry = [JSONLoader getEserlerToKategory:self.catId];
}
if ([arry count] >0)
{
self.eserList = arry;
for (EserFiles*eserfile in self.eserList) {
// NSLog(#"sayı :%d %#",eserfile.eser.esersayi,eserfile.eser.kisaisim);
[skulist addObject:eserfile.eser.eserstokkod];
}
// dispatch_async( dispatch_get_main_queue(),
// ^{
[self storkontrol:skulist];
// });
} else {
dispatch_async( dispatch_get_main_queue(),^{
[spinnerorta stopAnimating];
[self sitedeveriyokbilgi];
});
}
});
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
int count = self.eserList.count;
return count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// [collectionView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
EserFiles *esefiles =[self.eserList objectAtIndex:indexPath.row];
Eser *eser = esefiles.eser;
UrunCell *urunCell = [collectionView dequeueReusableCellWithReuseIdentifier:#"UrunCell" forIndexPath:indexPath];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake((urunCell.frame.size.width-25)/2, 50, 24, 24);
[spinner startAnimating];
[urunCell.contentView addSubview: spinner];
NSString *title = #"";
if ([eser.kisaisim isKindOfClass:[NSNull class]] || [eser.kisaisim isEqualToString:#""]){
title = eser.isim;
} else title = eser.kisaisim;
urunCell.UrunIsim.text=title;
// NSLog(#"title : %#",title);
[urunCell.UrunImage sd_setImageWithURL:[NSURL URLWithString:eser.kapakYol]
placeholderImage:[UIImage imageNamed:#"placeholder"] options:indexPath.row == 0 ? SDWebImageRefreshCached : 0];
[spinner stopAnimating];
return urunCell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
self.vitrinDetayViewController =[self.storyboard instantiateViewControllerWithIdentifier:#"VitrinDetayViewController"];
EserFiles *esefiles =[self.eserList objectAtIndex:indexPath.row];
self.vitrinDetayViewController.eser = esefiles;
[self.navigationController pushViewController:self.vitrinDetayViewController animated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
// [self.myCollectionView setContentOffset:CGPointZero animated:NO];
[super viewWillAppear:animated];
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.myCollectionView.collectionViewLayout;
// collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
//[self.myCollectionView setContentOffset:CGPointZero animated:NO];
// self.automaticallyAdjustsScrollViewInsets = NO;
[spinnerorta stopAnimating];
}

RSS Feed Won't Load

I have a tableview that shows data from an RSS feed and it works fine as long as it is not the root view of my app. I have always shown it by pressing a button but now I'm wanting to have it be the first view the user sees but the activity indicator just keeps spinning and the content never loads. Like I said, when I've pushed it onto the navigation stack from a button, it loads the content so I'm not really sure why it won't load when it's the first view shown.
AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
AgStoriesViewController *rootView = [[AgStoriesViewController alloc] initWithNibName:nil bundle:nil];
WebViewController *wvc = [[WebViewController alloc]init];
[rootView setWebViewController:wvc];
KFBNavControllerViewController *navController = [[KFBNavControllerViewController alloc] initWithRootViewController:rootView];
navController.delegate = rootView;
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
}
TableView with RSS
#import "AgStoriesViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "DTCustomColoredAccessory.h"
#import "UIImage+ImageEffects.h"
#import "UIView+Borders.h"
#import "TSMessage.h"
#import "TSMessageView.h"
#import "ArticleCell.h"
#import "KFBAppDelegate.h"
#import "MenuTableViewController.h"
#implementation AgStoriesViewController
{
UIActivityIndicatorView *loadingIndicator;
}
#synthesize webViewController, blurredView, contentView, menuShown;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.navigationController.delegate = self;
}
return self;
}
- (void)viewDidLoad
{
menuShown = NO;
UIImage *background = [UIImage imageNamed:#"sunset"];
UIImageView *backgroundImageView = [[UIImageView alloc]initWithImage:background];
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.tableView.backgroundView = backgroundImageView;
self.title = #"Ag News";
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
UIImage *hamburgerButton = [UIImage imageNamed:#"list_button"];
UIBarButtonItem *listButton = [[UIBarButtonItem alloc]initWithImage:hamburgerButton style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
self.navigationItem.leftBarButtonItem = listButton;
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
}
else
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(142, 365, 37, 37)];
}
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
loadingIndicator.hidesWhenStopped = YES;
[self.tableView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
}
- (void)showMenu
{
if (!menuShown)
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
contentView = [[UIView alloc]initWithFrame:self.tableView.bounds];
contentView.autoresizesSubviews = YES;
contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
contentView.backgroundColor = [UIColor clearColor];
blurredView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[blurredView setBarStyle:UIBarStyleBlack];
[blurredView setBarTintColor:kfbBlue];
MenuTableViewController *menu = [[MenuTableViewController alloc]initWithNibName:#"MenuTableViewController" bundle:nil];
menu.view.frame = CGRectMake(0, 0, screenWidth, screenHeight - 50);
[self.view addSubview:contentView];
[contentView addSubview:blurredView];
[self addChildViewController:menu];
[contentView addSubview:menu.view];
self.tableView.scrollEnabled = NO;
menuShown = YES;
}
else if (menuShown)
{
[contentView removeFromSuperview];
[blurredView removeFromSuperview];
self.navigationController.navigationBarHidden = NO;
self.tableView.scrollEnabled = YES;
menuShown = NO;
}
}
- (void)closeMenu
{
[contentView removeFromSuperview];
self.navigationController.navigationBarHidden = NO;
self.tableView.scrollEnabled = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
[loadingIndicator stopAnimating];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"])
{
channel = [[RSSChannel alloc]init];
[channel setParentParserDelegate:self];
[parser setDelegate:channel];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"channel items %lu", (unsigned long)[[channel items]count]);
return [[channel items]count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 215;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RSSItem *item = [[channel items]objectAtIndex:[indexPath row]];
ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:#"articleCell"];
if (!cell)
{
NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:#"ArticleCell" owner:self options:NULL];
cell = [nibs firstObject];
}
cell.articleTitle.text = [item title];
cell.articleDescription.text = [item infoString];
cell.articleTitle.textColor = [UIColor whiteColor];
cell.articleDescription.textColor = [UIColor whiteColor];
cell.articleTitle.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:22.0];
cell.articleDescription.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:16.0];
cell.backgroundColor = [UIColor clearColor];
return cell;
}
- (void)fetchEntries
{
xmlData = [[NSMutableData alloc]init];
NSURL *url = [NSURL URLWithString:#"http://kyfbnewsroom.com/category/ag-news/feed"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
[self fetchEntries];
}
return self;
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
[loadingIndicator stopAnimating];
UIImage *background = [UIImage imageNamed:#"sunset"];
UIImage *effectImage = [background applyDarkEffect];
UIImageView *blurredBackground = [[UIImageView alloc]init];
blurredBackground.image = effectImage;
self.tableView.backgroundView = blurredBackground;
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];
// Give it a delegate
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
NSMutableArray *actionAlerts = [NSMutableArray array];
for (RSSItem *object in channel.items)
{
if (object.isActionAlert)
{
[actionAlerts addObject:object];
}
}
for (RSSItem *object in actionAlerts)
{
[channel.items removeObject:object];
}
// Reload the table
[[self tableView]reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we're done with it
connection = nil;
// Release the xmlData object, we're done with it
xmlData = nil;
[loadingIndicator stopAnimating];
// Grab the description of the error object passed to us
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view with this error displayed
// UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// [av show];
[TSMessage showNotificationWithTitle:#"Network Error" subtitle:errorString type:TSMessageNotificationTypeError];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
[[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"about:blank"]]];
[self.navigationController pushViewController:webViewController animated:YES];
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[webViewController webView]loadRequest:req];
webViewController.hackyURL = url;
}
else
{
[[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"about:blank"]]];
NSMutableArray *details = [self.splitViewController.viewControllers mutableCopy];
UINavigationController *detailNav = [[UINavigationController alloc]initWithRootViewController:webViewController];
[details replaceObjectAtIndex:1 withObject:detailNav];
KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
appDelegate.splitViewController.viewControllers = details;
appDelegate.window.rootViewController = self.splitViewController;
appDelegate.splitViewController.delegate = webViewController;
[appDelegate.splitViewController viewWillAppear:YES];
// Grab the selected item
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
// Construct a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];
// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Load the request into the web view
[[webViewController webView]loadRequest:req];
webViewController.hackyURL = url;
// Set the title of the web view controller's navigation item
[[webViewController navigationItem]setTitle:[entry title]];
}
}
#end
Use this method to reload your table data -
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
[[self tableView]reloadData];
}
This method is called when parsing of your xml document is finished. You are reloading table when data is not properly set in array, so it is showing you empty table.
EDIT -
Call connection method properly on view Initialization.
fetchEntries needs to be called in viewDidLoad.

Passing data between views and load a string to Text View

I have a NSMutableArray in a view where I parse some JSON data to a Table View. Now, when I click on a cell I want to pass the value (text) of the selected cell array to a UITextView in another view.
The NSMutableArray where I store the data is called movies.
Here's my code for the first view:
#interface DEMOSecondViewController ()
#end
#implementation DEMOSecondViewController
#synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
#synthesize fontForCellText;
#synthesize btnFaceBook, btnTwitter, btnTwitter2;
#synthesize strURLToLoad;
#synthesize movies;
- (IBAction)showButtonMenu {
[self.frostedViewController presentMenuViewController];
}
- (void)refresh:(UIRefreshControl *)refreshControl {
[refreshControl endRefreshing];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl setTintColor:[UIColor greenColor]];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
strURLToLoad = [[NSMutableString alloc] init];
[btnFaceBook setTitle:#"link-1" forState:UIControlStateDisabled];
[btnTwitter setTitle:#"link-2" forState:UIControlStateDisabled];
[btnTwitter2 setTitle:#"link-3" forState:UIControlStateDisabled];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PostsObject" owner:self options:nil];
PostsObject *cell = [nib objectAtIndex:0];
fontForCellText = cell.title.font;
cellTextWidth = cell.title.frame.size.width;
cellHeightExceptText = cell.frame.size.height - cell.title.frame.size.height;
[self.navigationController setNavigationBarHidden:YES];
self.tableView.separatorColor = [UIColor clearColor];
self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicatorView.color = [UIColor greenColor];
self.activityIndicatorView.hidesWhenStopped = YES;
self.activityIndicatorView.center = self.view.center;
[self.view addSubview:self.activityIndicatorView];
[self.activityIndicatorView startAnimating];
self.tableView.separatorColor = [UIColor clearColor];
movies = [[NSMutableArray alloc] init];
[self btnFromTabBarClicked:btnFaceBook];
}
- (void)loadJSONFromCurrentURL
{
[self.activityIndicatorView startAnimating];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[movies setArray:JSON];
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;
sender.selected = YES;
[strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];
[self loadJSONFromCurrentURL];
}
// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return movies.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
static NSString *Identifier1 = #"TableHeaderView";
TableHeaderView *cell = [tableView dequeueReusableCellWithIdentifier:Identifier1];
if (cell == nil) {
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:#"TableHeaderView" owner:self options:nil];
cell = (TableHeaderView *)[nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
} else {
static NSString *Identifier2 = #"PostsObject";
PostsObject *cell = [tableView dequeueReusableCellWithIdentifier:Identifier2];
if (cell == nil) {
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:#"PostsObject" owner:self options:nil];
cell = (PostsObject *)[nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *strText = [movie objectForKey:[self getTextKey]];
CGRect rect = cell.title.frame;
rect.size.height = [self getHeightForText:strText];
cell.title.frame = rect;
cell.title.text = strText;
cell.arrow.center = CGPointMake(cell.arrow.frame.origin.x, rect.origin.y + rect.size.height/2);
cell.published.text = [movie objectForKey:[self getPostedTime]];
cell.twitterName.text = [movie objectForKey:[self getTwitterName]];
return cell;
}
return 0;
}
//When I click on the cell, I want the selected cell-text to pass to another view
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//How can I do this?
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0) {
return 224;
} else {
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *strText = [movie objectForKey:[self getTextKey]];
CGFloat cellHeight = cellHeightExceptText + [self getHeightForText:strText];
return cellHeight;
}
}
- (NSString *)getTextKey
{
return btnTwitter.selected?#"tweet":#"message";
}
- (NSString *)getPostedTime
{
return btnTwitter.selected?#"posted":#"published";
}
- (NSString *)getTwitterName
{
return btnTwitter2.selected?#"user":#"usernew";
}
- (CGFloat)getHeightForText:(NSString *)strText
{
CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"labelSize.height = %f",labelSize.height);
return labelSize.height;
}
#end
And the code so far for the Second View looks like this:
#interface PostsNextView : UIViewController
#property (nonatomic, retain) NSDictionary *theMovie;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#end
So how can I get the value from the first view to pass and display in the Text View in this file?
Add to didSelectRowAtIndexPath code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//get the data you want to pass
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
// Allocate second view you want to open
PostsNextView *newView = [[PostsNextView alloc] init];
// pass the data
newView.theMovie = movie;
// present view
[self.navigationController pushViewController:newView animated:YES];
}
And in PostsNextView.m file in viewDidLoad you can show the text you want to show.
//Extended
Add property to keep track which button was pressed:
#interface PostsNextView : UIViewController
#property (nonatomic, retain) NSDictionary *theMovie;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#property int whichButton;
#end
in view did load add this line:
newView.theMovie = movie;
newView.whichButton = _witchBtn;
In your DEMOSecondViewController.m file add ivar:
#implementation DEMOSecondViewController
{
int _witchBtn;
}
And in the same file assign value to _witchBtn for example 0 as a default (all buttons disabled) if you change it to let's say Facebook assign _witchBtn = 1, if twitter _witchBtn = 2, etc.

UITableView for Forms Crashes

I have a UITableViewController that I'm using for a form. Each cell has a UILabel and a UITextField. When I tap on a UITextField, the keyboard comes up, then I scroll down and the cell goes off screen, when I tap on another UITextField, the app crashes.
This is my cell subclass.
#implementation EditorFieldCell
- (id)init
{
self = [super init];
if (self) {
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview:self.nameLabel];
[self.contentView addSubview:self.textField];
}
return self;
}
- (void)setName:(NSString *)name
{
_name = name;
CGRect frame = self.nameLabel.frame;
frame.size.width = roundf([_name sizeWithFont:[UIFont boldSystemFontOfSize:17.0f]].width);
self.nameLabel.frame = frame;
frame = self.textField.frame;
frame.size.width = self.frame.size.width - 16.0f - 14.0f - 14.0f - self.nameLabel.frame.size.width;
frame.origin.x = 16.0f + 14.0f + self.nameLabel.frame.size.width;
self.textField.frame = frame;
self.nameLabel.text = _name;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
self.textField.placeholder = placeholder;
}
- (void)setText:(NSString *)text
{
_text = text;
self.textField.text = text;
}
- (UILabel*)nameLabel
{
if (_nameLabel)
{
return _nameLabel;
}
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(16.0f, 0.0f, 0.0f, self.frame.size.height)];
_nameLabel.font = [UIFont boldSystemFontOfSize:17.0f];
return _nameLabel;
}
- (UITextField*)textField
{
if (_textField)
{
return _textField;
}
_textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, self.frame.size.height)];
_textField.font = [UIFont systemFontOfSize:17.0f];
_textField.textAlignment = NSTextAlignmentRight;
_textField.keyboardAppearance = UIKeyboardAppearanceDark;
return _textField;
}
#end
And here is my table subclass.
#interface ManageWineViewController ()
#end
#implementation ManageWineViewController
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
self.title = #"Manage Wine";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(done)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Save" style:UIBarButtonItemStyleDone target:self action:#selector(save)];
NSMutableArray *data = [[NSMutableArray alloc] init];
NSMutableDictionary *section = [[NSMutableDictionary alloc] init];
NSMutableArray *sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Estate", #"placeholder": #""}];
[sectionData addObject:#{#"name": #"Wine", #"placeholder": #""}];
[sectionData addObject:#{#"name": #"Vintage", #"placeholder": #"", #"keyboardType": [NSNumber numberWithInt:UIKeyboardTypeDecimalPad]}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
section = [[NSMutableDictionary alloc] init];
sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Type"}];
[sectionData addObject:#{#"name": #"Style", #"placeholder": #"Select a Style", #"options": #[#"", #"Red", #"White", #"Rosé", #"Sparkling", #"Saké", #"Dessert, Sherry, and Port"]}];
[sectionData addObject:#{#"name": #"Appellation", #"placeholder": #""}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
section = [[NSMutableDictionary alloc] init];
sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Alcohol %", #"placeholder": #"", #"keyboardType": [NSNumber numberWithInt:UIKeyboardTypeDecimalPad]}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
self.data = data;
self.inputTexts = [[NSMutableDictionary alloc] initWithDictionary:#{#"0": #"",
#"1": #"",
#"2": #"",
#"10": #"",
#"11": #"",
#"12": #"",
#"20": #""}];
}
return self;
}
- (void)done
{
[self.currentTextField resignFirstResponder];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)save
{
[self done];
}
- (void)hidePicker
{
[self.selectActionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.data.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ((NSArray*)[[self.data objectAtIndex:section] objectForKey:#"data"]).count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *cellInfo = [((NSArray*)[[self.data objectAtIndex:indexPath.section] objectForKey:#"data"]) objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"EditorCell";
EditorFieldCell *cell = (EditorFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[EditorFieldCell alloc] init];
}
cell.textField.tag = [[NSString stringWithFormat:#"%i%i", indexPath.section, indexPath.row] integerValue];
cell.textField.delegate = self;
cell.name = cellInfo[#"name"];
cell.placeholder = cellInfo[#"placeholder"];
cell.text = [self.inputTexts objectForKey:[NSString stringWithFormat:#"%i", cell.textField.tag]];
if (cellInfo[#"keyboardType"])
{
cell.textField.keyboardType = [cellInfo[#"keyboardType"] integerValue];
}
else
{
cell.textField.keyboardType = UIKeyboardTypeDefault;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark - UITextFieldDelegate methods
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.currentTextField = textField;
if (textField.tag == 11)
{
//show select
NSArray *options = [[[[self.data objectAtIndex:1] objectForKey:#"data"] objectAtIndex:1] objectForKey:#"options"];
self.selectTextField = textField;
self.selectOptions = options;
[textField resignFirstResponder];
self.selectActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
self.selectPickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
self.selectPickerView.showsSelectionIndicator = YES;
self.selectPickerView.dataSource = self;
self.selectPickerView.delegate = self;
[self.selectActionSheet addSubview:self.selectPickerView];
[self.selectActionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[self.selectActionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[self.inputTexts setObject:textField.text forKey:[NSString stringWithFormat:#"%i", textField.tag]];
return YES;
}
#end
The error that I am getting with the crash is:
*** -[EditorFieldCell _didChangeToFirstResponder:]: message sent to deallocated instance 0x155f6e20
This is iOS 7 (and will only support iOS 7) if that helps.
You are not initialising EditorFieldCell with reuse identifier.
EditorFieldCell *cell = (EditorFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
This condition will false.
if (!cell)
{
cell = [[EditorFieldCell alloc] init];
}
Try to create cell with reuseIdentifier
cell = [[EditorFieldCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
And write this in EditorFieldCell.m
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview:self.nameLabel];
[self.contentView addSubview:self.textField];
}
}

Filtering a TableView with sections

I try to make a little program to learn more about searching a tableview about a searchbar. Meanwhile i'm in the third week trying to do this. I found many examples in different ways in the internet. The most with a searchdisplaycontroller but this way is only for a viewcontroller. i prefer a way that also works with an uiview and so i use the searchbar delegatemethod to filter my data dictionary. Normally i try as long i get handle such things by myself. But this is my nemesis. I really can't find a way to get this problem solved. Can anyone help me with my code?
Here it is.
#import "FilterDemoTableViewController.h"
#implementation FilterDemoTableViewController
#synthesize filteredTableData;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize tableContents;
#synthesize Keys;
- (void)viewDidLoad
{
[super viewDidLoad];
searchBar.delegate = (id)self;
//-----------------------My TableView Data ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
//--------------------------------------------------------------------------
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered) {
return [filteredTableData count];
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
int rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = [listData count];
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSDictionary* sectionDictionary;
if (isFiltered) {
sectionDictionary = [filteredTableData objectAtIndex:indexPath.section];
} else {
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
}
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
//I think here is something wrong but i don't know what
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in tableContents) //dictionary read
{
NSArray *array = [dictionary objectForKey:Keys]; //section of dictionary read
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
[filteredTableData addObject:sTemp];
}
}
[self.tableView reloadData];
}
- (void)viewDidUnload{
[self setSearchBar:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Now i post a complete refreshed code. I tested each component of the code step by step. It works and the search is also fine (in a UITableViewController). But in this example the hole code is in a UIView. The reason, on this way it is possible to create non full-size tableviews and instanzes of tableviews. Much better for a clear Viewcontroller. I know that an UIView has no method like this reloadData but it is necessary.
Near the code end you can see the problem line. And for this last step i have no idea how i can solve this. [self.tableView reloadData];
#import "TableView.h"
#import <QuartzCore/QuartzCore.h>
#interface TableView ()
#end
#implementation TableView
#synthesize delegate;
#synthesize dropDownHeight;
#synthesize labelText;
#synthesize enabled;
#synthesize tableContents;
#synthesize Keys;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize filteredTableData;
- (void)__show {
viewControl.alpha = 0.0f;
UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
[mainWindow addSubview:viewControl];
[UIView animateWithDuration:0.3f
animations:^{
viewControl.alpha = 1.0f;
}
completion:^(BOOL finished) {}];
}
- (void)__hide {
[UIView animateWithDuration:0.2f
animations:^{
viewControl.alpha = 0.0f;
}
completion:^(BOOL finished) {
[viewControl removeFromSuperview];
}];
}
- (void) setLabelText:(NSString *)_labelText{
[button setTitle:labelText forState:UIControlStateNormal];
}
- (void) setEnable:(BOOL)_enabled{
enabled = _enabled;
[button setEnabled:_enabled];
}
- (void) setArrayData:(NSArray *)_arrayData{
[table reloadData];
}
- (void) buttonPressed{
[self __show];
}
- (void) controlPressed{
//[viewControl removeFromSuperview];
[self __hide];
}
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(10, 0, 280, 30)];
[button setTitle:#"--Auswahl--" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"combo_bg.png"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:14]];
[self addSubview:button];
dropDownHeight = 706;
viewControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
[viewControl addTarget:self action:#selector(controlPressed) forControlEvents:UIControlEventTouchUpInside];
CGFloat x = self.frame.origin.x;
CGFloat y = (viewControl.frame.size.height - dropDownHeight)/2;
table = [[UITableView alloc] initWithFrame:CGRectMake(x, y, frame.size.width, dropDownHeight) style:UITableViewStyleGrouped];
table.dataSource = self;
table.delegate = self;
searchBar = [[UISearchBar alloc] init];
[searchBar sizeToFit];
searchBar.delegate = (id)self;
table.tableHeaderView = searchBar;
CALayer *layer = table.layer;
layer.masksToBounds = YES;
layer.cornerRadius = 2.0f;
layer.borderWidth = 1.0f;
[layer setBorderColor:[UIColor darkGrayColor].CGColor];
[viewControl addSubview:table];
CGAffineTransform rotateTable = CGAffineTransformMakeRotation(M_PI_2);
table.transform = rotateTable;
table.frame = CGRectMake(-2, -1, table.frame.size.width, table.frame.size.height);
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"gradientBackground.png"]];
[tempImageView setFrame:self->table.frame];
table.backgroundView = tempImageView;
//----------------------- TableView Daten ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",#"Hamburg",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
// ---------------------------------------------------------------------
}
return self;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
return 40;
}
else {
return 0;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(20, 6, 300, 30);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
label.shadowColor = [UIColor grayColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
[view addSubview:label];
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
return [self.Keys objectAtIndex:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered)
{
return 1;
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self.isFiltered)
{
rowCount = [filteredTableData count];
}
else
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
rowCount = [listData count];
}
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
if (isFiltered)
{
NSString * stadt = [filteredTableData objectAtIndex:indexPath.row];
cell.textLabel.text = stadt;
}
else
{
NSDictionary* sectionDictionary;
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:[indexPath section]]];
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedIndex = [indexPath row];
[self __hide];
[button setTitle:[[NSString alloc] initWithFormat:rowValue] forState:UIControlStateNormal];
}
- (NSInteger) selectedIndex {
return selectedIndex;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
[filteredTableData removeAllObjects];
for (NSString* key in self.tableContents)
{
NSArray *staedte = [self.tableContents objectForKey:key];
for (NSString *stadt in staedte)
{
NSRange titleResultsRange = [stadt rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
{
[filteredTableData addObject:stadt];
}
}
}
}
[self.tableView reloadData]; //Here is the error
}
-(void)didChangeTableViewValue:(TableView *)TableView selectedIndex:(NSInteger)selectedIndex {
}
#end

Resources