UIActivityIndicatorView not show at UItableViewcell - ios

in the
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row==[self.peopleDataController countOfList]){
static NSString *CellIdentifier = #"LastMoreCell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
moreButton = [[UIButton alloc] initWithFrame:CGRectMake(140, 2, 42, 42)];
[moreButton setImage:[UIImage imageNamed:#"more.png"] forState:UIControlStateNormal];
[moreButton addTarget:self action:#selector(showMoreRows:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:moreButton];
return cell;
}
}
-(void) showMoreRows:(id)sender {
MyAuraAppDelegate *delegate = (MyAuraAppDelegate *) [[UIApplication sharedApplication] delegate];
refreshlast = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.hidesWhenStopped = YES;
refreshlast.center = CGPointMake([[sender superview] superview].bounds.size.width / 2.0f, [[sender superview] superview].bounds.size.height / 2.0f);
[sender setHidden:YES];
[[sender superview].superview addSubview: refreshSpinner];
[refreshlast startAnimating];
dispatch_queue_t dloadQueue = dispatch_queue_create("People refresh", NULL);
dispatch_async(dloadQueue, ^{
if ([[[GlobalVariable sharedInstance] peopleList] count] >0) {
_peopleDataController = [_peopleDataController initPeopleListWithCoordinate:delegate.locationCoordinate2D auraId:delegate.myToken offset:0];
NSLog(#"eerrrr %d",_peopleDataController.peopleList.count);
// _peopleDataController.peopleList=[[GlobalVariable sharedInstance] peopleList];
for (int i=0; i< [_peopleDataController.peopleList count]; i++) {
[[[GlobalVariable sharedInstance] peopleList ] addObject:[_peopleDataController.peopleList objectAtIndex:i]];
}
_peopleDataController.peopleList =[[GlobalVariable sharedInstance] peopleList] ;
NSLog(#"eerrr33r %d",_peopleDataController.peopleList.count);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self performSelector:#selector(addItem) withObject:nil afterDelay:2.0];
});
});
dispatch_release(dloadQueue);
}
but my UIActivityIndicatorView refresh last not show,can you give me some clue?

i found my mistake is :[sender superview].superview is the tabview not the tableviewcell
so last i modify my code:
-(void) showMoreRows:(id)sender {
UIButton *button=(UIButton*)sender;
MyAuraAppDelegate *delegate = (MyAuraAppDelegate *) [[UIApplication sharedApplication] delegate];
refreshlast = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.hidesWhenStopped = YES;
UITableViewCell *lastcell=(UITableViewCell*)[button superview];
refreshlast.center = CGPointMake(lastcell.frame.size.width / 2.0f, lastcell.frame.size.height / 2.0f);
NSLog(#"ddd %f",lastcell.frame.size.height);
[button setHidden:YES];
[lastcell addSubview:refreshlast];
[refreshlast startAnimating];
dispatch_queue_t dloadQueue = dispatch_queue_create("People refresh", NULL);
dispatch_async(dloadQueue, ^{
if ([[[GlobalVariable sharedInstance] peopleList] count] >0) {
_peopleDataController = [_peopleDataController initPeopleListWithCoordinate:delegate.locationCoordinate2D auraId:delegate.myToken offset:0];
NSLog(#"eerrrr %d",_peopleDataController.peopleList.count);
// _peopleDataController.peopleList=[[GlobalVariable sharedInstance] peopleList];
for (int i=0; i< [_peopleDataController.peopleList count]; i++) {
[[[GlobalVariable sharedInstance] peopleList ] addObject:[_peopleDataController.peopleList objectAtIndex:i]];
}
_peopleDataController.peopleList =[[GlobalVariable sharedInstance] peopleList] ;
NSLog(#"eerrr33r %d",_peopleDataController.peopleList.count);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self performSelector:#selector(addItem) withObject:nil afterDelay:2.0];
});
});
dispatch_release(dloadQueue);
}

Related

How can I reload the price of product by clicking on select the quantity in table view in iOS?

In this, I am clicking on update button and my price is not updating instantly, Its updating when i go back to home view controller. Please help me out of this.[I want when I click on update button, My price of product will be change according to selection of quantity like 1 kg, 2kg ,5 kg etc]
#import "MainCartViewController.h"
#import "CartTableCell.h"
#import "CheckOutViewController.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "Detail.h"
#import "MBProgressHUD.h"
#define JSON_URL #"http://www.webchefz.com/Andriod/index.php?Table=Cart&UserID=11"
#interface MainCartViewController ()
#end
#implementation MainCartViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:NO animated:YES];
UINavigationBar *navBar = [[self navigationController] navigationBar];
[ navBar setTintColor:[UIColor whiteColor]];
UIButton *Btn =[UIButton buttonWithType:UIButtonTypeCustom];
[Btn setFrame:CGRectMake(0.0f,0.0f,30.0f,30.0f)];
[Btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:#"carc.png"]] forState:UIControlStateNormal];
[Btn addTarget:self action:#selector(AddtoCartButton:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:Btn];
cFRAIPArray = [[NSMutableArray alloc]init];
tableData =[[NSMutableArray alloc]init];
blogURL= [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
tableData = [dataDictionary objectForKey:#"userlist"];
// int tp = [NSString stringWithFormat:#"%d",[dataDictionary valueForKey:#"TotalPrice"]];
totalPrice= [[dataDictionary objectForKey:#"userlist"]valueForKey:#"TotalPrice"];
NSLog(#"TP IS %#", [dataDictionary valueForKey:#"TotalPrice"]);
subtotal.text= [[NSString alloc] initWithFormat:#"%# Rs.",[dataDictionary valueForKey:#"TotalPrice"]];
int ShippingValue = [[subtotal text] intValue];
int value = 50;
float floatNum = ShippingValue + value;
grandTotal.text=[[NSString alloc] initWithFormat:#"%.1f Rs.", floatNum];
NSLog(#"dwfefefeusers are %#", totalPrice);
NSLog(#"dwfefefeusers are %#", tableData);
NSString *items= [[dataDictionary objectForKey:#"userlist"]valueForKey:#"Name"];
NSLog(#"hjdbhsdbchjds%#",items
);
for (dataDictionary in tableData)
{
// currentHotel= [[Detail alloc]initWithId:[[bpDictionary objectForKey:#"id"]integerValue] Name:[bpDictionary objectForKey:#"Name"] HindiName:[bpDictionary objectForKey:#"HindiName"] MRP:[[bpDictionary objectForKey:#"MRP"]integerValue] ImagePath:[bpDictionary objectForKey:#"ImagePath"]Category:[bpDictionary objectForKey:#"Category"]];
currentHotel = [[Detail alloc]initWithId:[[dataDictionary objectForKey:#"ID"]integerValue] Name:[dataDictionary objectForKey:#"Name"] HindiName:[dataDictionary objectForKey:#"HindiName"] MRP:[[dataDictionary objectForKey:#"TotalPrice"]integerValue] CartID:[[dataDictionary objectForKey:#"CartID"]integerValue] ProductID:[[dataDictionary objectForKey:#"ProductID"]integerValue] Quantity:[[dataDictionary objectForKey:#"Quantity"]integerValue] userName:[dataDictionary objectForKey:#"UserName"] ImagePath:[dataDictionary objectForKey:#"ImagePath"] Category:[dataDictionary objectForKey:#"Category"]];
[self.objectHolderArray addObject:currentHotel];
}
CGRect frame = CGRectMake(0, 0, 0, 44);
UILabel *label = [[UILabel alloc]initWithFrame:frame];
label.text = #"Cart List";
label.textColor=[UIColor whiteColor];
label.font = [UIFont fontWithName:#"Helvetica Neue" size:16];
self.navigationItem.titleView = label;
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Initialize table data
// tableData = [NSMutableArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto", #"Full Breakfast", #"Hamburger", #"Ham and Egg Sandwich", #"Creme Brelee", #"White Chocolate Donut", #"Starbucks Coffee", #"Vegetable Curry", #"Instant Noodle with Egg", #"Noodle with BBQ Pork", #"Japanese Noodle with Pork", #"Green Tea", #"Thai Shrimp Cake", #"Angry Birds Cake", #"Ham and Cheese Panini", nil];
}
-(NSMutableArray *)objectHolderArray
{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
IBAction)AddtoCartButton:(id)sender
{
MainCartViewController *cartView= [[MainCartViewController alloc]initWithNibName:#"MainCartViewController" bundle:nil];
[self.navigationController pushViewController:cartView animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CartTableCell";
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CartTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.item];
NSLog(#"%#",[self.objectHolderArray
objectAtIndex:indexPath.item] );
cell.nameLabel.text=currentHotel.name;
cell.MRPLabel.text=[NSString stringWithFormat:#"Rs.%d",currentHotel.MRP];
NSLog(#"price is %#",cell.MRPLabel.text);
[cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:currentHotel.images] placeholderImage:[UIImage imageNamed:#"defaultPlayerImge.png"] options:SDWebImageRefreshCached|SDWebImageProgressiveDownload];
[cell.deleteBtn addTarget:self action:#selector(deleteProduct:) forControlEvents:UIControlEventTouchUpInside];
cell.deleteBtn.tag = [indexPath row];
[cell.PickerBtn addTarget:self action:#selector(createPickerView:) forControlEvents:UIControlEventTouchUpInside];
cell.PickerBtn.tag = [indexPath row];
[cell.updateBtn addTarget:self action:#selector(updateProduct:) forControlEvents:UIControlEventTouchUpInside];
cell.updateBtn.tag = [indexPath row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debtn.deleteBtn.highlighted) {
NSLog(#"cff");
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.objectHolderArray count];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
int errorCode = httpResponse.statusCode;
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString];
NSLog(#"response is %d, %#", errorCode, fileMIMEType);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(#"data is %#", data);
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string is %#", myString);
NSError *e = nil;
flickrDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSLog(#"dictionary is %#", flickrDictionary);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[HUD hide:YES];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Quanity updated succesfully" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.tableView1 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView1 reloadData];
// }
NSLog(#"cfraiparray %#", cFRAIPArray);
NSLog(#"Succeeded!");
}
-(void)createPickerView :(UIButton *)button
{
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
self.pickerViewTextField = [[UITextField alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.pickerViewTextField];
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
weights= [[NSMutableArray alloc] initWithObjects:#"1 Kg",#"2 Kg",#"5 Kg",#"10 Kg",#"50 Kg",
nil];
// set change the inputView (default is keyboard) to UIPickerView
self.pickerViewTextField.inputView = pickerView;
// add a toolbar with Cancel & Done button
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneTouched:)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancelTouched:)];
[toolBar setItems:[NSArray arrayWithObjects:cancelButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], doneButton, nil]];
self.pickerViewTextField.inputAccessoryView = toolBar;
[self.pickerViewTextField becomeFirstResponder];
// [self.view addSubview:pickerView];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
// [self bringUpPickerViewWithRow:indexPath];
}
-(void) deleteProduct:(UIButton *)button
{
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.webchefz.com/Andriod/delete.php?Table=Cart&CartID=%d&UserID=11",currentHotel.CartID]];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:myRequest delegate:self];
NSLog(#"main cart id is %#", [NSString stringWithFormat:#"%d",currentHotel.CartID]);
NSLog(#"ded");
[self.objectHolderArray removeObjectAtIndex:button.tag];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
[self.tableView1 deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView1 reloadData];
}
-(void) updateProduct:(UIButton *)button
{
HUD= [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.labelText = #"Please Wait...";
HUD.mode = MBProgressHUDModeIndeterminate;
[self.view addSubview:HUD];
[HUD show:YES];
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.webchefz.com/Andriod/update.php?Table=Cart&CartID=%d&Quantity=%d&UserID=11&ProductID=%d",currentHotel.CartID,pickerQuantity,currentHotel.ProductID]];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:myRequest delegate:self];
NSLog(#"main cart id is %#", [NSString stringWithFormat:#"%d",currentHotel.ProductID]);
NSLog(#"ded%#",[NSString stringWithFormat:#"%d",currentHotel.CartID]);
// [self.tableView1 insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
// [self.objectHolderArray removeObjectAtIndex:button.tag];
self.tableView1.delegate = self;
self.tableView1.dataSource = self;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
[self.tableView1 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView1 reloadData];
}
- (void)cancelTouched:(UIBarButtonItem *)sender
{
// hide the picker view
[self.pickerViewTextField resignFirstResponder];
}
- (void)doneTouched:(UIBarButtonItem *)sender
{
// hide the picker view
[self.pickerViewTextField resignFirstResponder];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
NSIndexPath *indexPath ;
if ([self.objectHolderArray objectAtIndex:indexPath.row])
{
if ([[weights objectAtIndex:row]isEqual:#"1 Kg"])
{
pickerQuantity=1;
[self.pickerViewTextField becomeFirstResponder];
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"2 Kg"])
{
pickerQuantity=2;
selectWeight.hidden=YES;
[self.pickerViewTextField becomeFirstResponder];
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"5 Kg"]) {
pickerQuantity=5;
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"10 Kg"]) {
pickerQuantity=10;
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else{
pickerQuantity=50;
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}}
selectWeight.hidden=YES;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 30;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
//---number of items(rows) in the Picker View---
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [weights count];
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
// self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
// [self.view addSubview:selectWeight];
//
//
// // Get the text of the row.
NSString *rowItem = [weights objectAtIndex: row];
////
UILabel *lblRow = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView bounds].size.width, 44.0f)];
[lblRow setTextAlignment:UITextAlignmentCenter];
[lblRow setTextColor: [UIColor blackColor]];
[lblRow setText:rowItem];
lblRow.font = [UIFont fontWithName:#"Verdana" size:12];
[lblRow setBackgroundColor:[UIColor clearColor]];
return lblRow;
}
#end
You should just call [tableView reloadData], to update info inside table view each time.

How to load more data in collectionviewcontroller

I had a little problem which is I can't properly reload a new data in collectionview whilst scrolling down at the bottom of collectionviewcontroller. The problem I had starting at this code if (indexPath.row == [selectedVideoData count] - 1). Below is my full code for collectionviewcontroller :
#import "PageVideosCVC.h"
#import "facebook.h"
#import "MBProgressHUD.h"
#import <AFNetworking/AFNetworking.h>
#import <AVFoundation/AVFoundation.h>
#import <SDWebImage/UIImageView+WebCache.h>
#interface PageVideosCVC () <UICollectionViewDataSource,UICollectionViewDelegate>
#end
#implementation PageVideosCVC
#synthesize selectedVideoData, selectNextVideoData;
static NSString * const reuseIdentifier = #"Cell";
-(void) viewWillAppear:(BOOL)animated {
UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
[UINavigationBar appearance].barTintColor = [UIColor lightGrayColor];
[self.view addSubview: navBar];
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:#"< Back"
style:UIBarButtonItemStylePlain
target:self
action:#selector(backButtonTapped:)];
// UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:#"Done"
// style:UIBarButtonItemStyleBordered
// target:self action:nil];
NSString *selectedPageName = [[NSString alloc] initWithFormat:#"%#", self.pageName];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:selectedPageName];
// navItem.rightBarButtonItem = doneItem;
navItem.leftBarButtonItem = cancelItem;
navBar.items = [NSArray arrayWithObjects: navItem,nil];
[UIBarButtonItem appearance].tintColor = [UIColor blueColor];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
facebook *fb = [[facebook alloc] init];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSDictionary *fbVideoParams = #{ #"fields": #"videos.limit(10){source,description,thumbnails.limit(1),length}"};
[fb fetchVideoInformationFromPages:fbVideoParams videoID:self.videoID completionHandler:^(NSDictionary *videoResult) {
if (videoResult != nil) {
selectedVideoData = [videoResult valueForKeyPath:#"videos.data"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
}
}];
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = NO;
// Register cell classes
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
// Do any additional setup after loading the view.
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return selectedVideoData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// Configure the cell
// This is a last cell, I wanna load next video data from fb.
if (indexPath.row == [selectedVideoData count] - 1) {
NSString *fbToken = [facebook currentFBAccessToken];
NSString *fbNextVideoURL = [NSString stringWithFormat:#"https://graph.facebook.com/v2.5/606246146140197/videos?access_token=%#&pretty=0&fields=source,description,thumbnails.limit(1),length&limit=10&after=ODYxOTA5OTEzOTA3MTUx", fbToken];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[manager GET:fbNextVideoURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
selectNextVideoData = [responseObject valueForKey:#"data"];
NSLog(#"JSON Next Video: %#", selectNextVideoData);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
// I had a problem setting the right thumbnail here.
UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
NSURL *thumbnailImage = [NSURL URLWithString:[selectNextVideoData valueForKeyPath:#"thumbnails.data"]];
// NSLog(#"JSON Next Video: %#", thumbnailImage);
[imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
[self.collectionView reloadData];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
} else {
UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
NSURL *thumbnailImage = [NSURL URLWithString:[selectedVideoData valueForKeyPath:#"thumbnails.data.uri"][indexPath.row][0]];
[imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
return cell;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// NSLog(#"videos : %#", selectedVideoData);
// NSLog(#"videos source : %#", [selectedVideoData valueForKeyPath:#"source"][indexPath.row]);
NSURL *videoURL = [NSURL URLWithString:[selectedVideoData valueForKeyPath:#"source"][indexPath.row]];
self.playerController = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
[[self.playerController view] setFrame:[self.view bounds]]; // Frame must match parent view
[self.view addSubview:[self.playerController view]];
self.playerController.movieSourceType = MPMovieSourceTypeStreaming;
self.playerController.controlStyle = MPMovieControlStyleFullscreen;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doneButtonClick:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.playerController play];
// Play the video using AVPlayer iOS9 above
// AVPlayer *player = [AVPlayer playerWithURL:videoURL];
// AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
// playerLayer.frame = self.view.bounds;
// [self.view.layer addSublayer:playerLayer];
// [player play];
}
-(void)doneButtonClick:(NSNotification*)aNotification{
NSNumber *reason = [aNotification.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([reason intValue] == MPMovieFinishReasonUserExited) {
// Your done button action here
// [self dismissViewControllerAnimated:YES completion:nil];
NSLog(#"done button tapped");
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerDidExitFullscreenNotification
object:nil];
[self.playerController stop];
[self.playerController.view removeFromSuperview];
}
}
- (IBAction)backButtonTapped:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Perhaps rather than this approach you can try scrollView Delegate Methods :
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
// NSLog(#"offset: %f", offset.y);
// NSLog(#"content.height: %f", size.height);
// NSLog(#"bounds.height: %f", bounds.size.height);
// NSLog(#"inset.top: %f", inset.top);
// NSLog(#"inset.bottom: %f", inset.bottom);
// NSLog(#"pos: %f of %f", y, h);
float reload_distance = 10;
if(y > h + reload_distance) {
NSLog(#"load more rows");
}
}

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];
}

UIActivityIndicatorView Not Appearing

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.

Trouble with Cells in UITableView

I'm writing a simple checklist app. I have two UIViewControllers. The first displays the checklist in a UITableView. I'm using a UIBarButtonItem to push a second view onto the stack to add new tasks. All of the tasks are saved in an array.
Everything works great save for one thing.
If I enter edit mode and delete an item from the table view, the item is removed from the table view and the array--this part seems to be working fine. However, after deleting an item, if I tap the bar button item to add a new task, I run into a problem.
My NSLogs tell me that the new item is added to the array, but when I return to the table view, the deleted item shows up instead of the new item. The table view seems to be reusing the dequeued cell (not sure).
What am I doing wrong?
CLCheckListViewController.m
#import "CLCheckListViewController.h"
#import "CLTaskFactory.h"
#import "CLTaskStore.h"
#import "CLAddTaskViewController.h"
#implementation CLCheckListViewController
{
__weak IBOutlet UITableView *checkList;
}
- (id)init
{
self = [super init];
if (self) {
// add five sample tasks
CLTaskFactory *task1 = [[CLTaskFactory alloc] init];
[task1 setTaskName:#"Task 1"];
[task1 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task1];
CLTaskFactory *task2 = [[CLTaskFactory alloc] init];
[task2 setTaskName:#"Task 2"];
[task2 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task2];
CLTaskFactory *task3 = [[CLTaskFactory alloc] init];
[task3 setTaskName:#"Task 3"];
[task3 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task3];
CLTaskFactory *task4 = [[CLTaskFactory alloc] init];
[task4 setTaskName:#"Task 4"];
[task4 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task4];
CLTaskFactory *task5 = [[CLTaskFactory alloc] init];
[task5 setTaskName:#"Task 5"];
[task5 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task5];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[checkList reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// create edit button
[[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];
// create title
[[self navigationItem] setTitle:#"Checklist"];
// create add guest button
UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(pushAddTask)];
[[self navigationItem] setRightBarButtonItem:bbi];
}
- (void)pushAddTask
{
CLAddTaskViewController *advk = [[CLAddTaskViewController alloc] init];
[[self navigationController] pushViewController:advk animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[CLTaskStore sharedStore] allTasks] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [checkList dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;
}
return cell;
}
- (void)didCheckTask:(UIButton *)button
{
CGPoint hitPoint = [button convertPoint:CGPointZero toView:checkList];
hitIndex = [checkList indexPathForRowAtPoint:hitPoint];
task = [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[hitIndex row]];
if (task.didComplete) {
task.didComplete = NO;
} else {
task.didComplete = YES;
}
NSInteger taskCount = [[[CLTaskStore sharedStore] allTasks] count];
for (int i = 0; i < taskCount; i++) {
NSLog(#"%#, status: %#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:i], [[[[CLTaskStore sharedStore] allTasks] objectAtIndex:i] didComplete]?#"YES":#"NO");
}
// toggle checkbox
button.selected = !button.selected;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
// set editing mode
if (editing) {
self.navigationItem.title = #"Edit Checklist";
[checkList setEditing:YES];
} else {
self.navigationItem.title = #"Checklist";
[checkList setEditing:NO];
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// remove task
if (editingStyle == UITableViewCellEditingStyleDelete) {
// remove task from CLTaskStore
task = [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]];
[[CLTaskStore sharedStore] removeTask:task];
// remove guest from table view
[checkList deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// reload table view
//[checkList reloadData];
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
[[CLTaskStore sharedStore] moveTaskAtIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
}
#end
CLAddTaskViewController.m
#import "CLAddTaskViewController.h"
#import "CLTaskFactory.h"
#import "CLTaskStore.h"
#implementation CLAddTaskViewController
- (void)viewDidLoad
{
[[self navigationItem] setTitle:#"Add Task"];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// clear first responder
[[self view] endEditing:YES];
// create new task
CLTaskFactory *newTask = [[CLTaskFactory alloc] init];
[newTask setTaskName:[newTaskName text]];
// add new guest to RCGuestStore
[[CLTaskStore sharedStore] addTask:newTask];
}
#end
CLAddTaskFactory.m
#import "CLTaskFactory.h"
#implementation CLTaskFactory
#synthesize taskName;
- (void)setDidComplete:(BOOL)dc
{
didComplete = dc;
}
- (BOOL)didComplete
{
return didComplete;
}
- (NSString *)description
{
// override the description
NSString *descriptionString = [[NSString alloc] initWithFormat:#"%#", taskName];
return descriptionString;
}
#end
CLAddTaskStore.m
#import "CLTaskStore.h"
#import "CLTaskFactory.h"
#import "CLCheckListViewController.h"
#implementation CLTaskStore
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
+ (CLTaskStore *)sharedStore
{
static CLTaskStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[super allocWithZone:nil] init];
}
return sharedStore;
}
- (id)init
{
self = [super init];
if (self) {
allTasks = [[NSMutableArray alloc] init];
}
return self;
}
- (NSMutableArray *)allTasks
{
return allTasks;
}
- (void)addTask:(CLTaskFactory *)task
{
[allTasks addObject:task];
NSLog(#"Task added: %#", task);
}
- (void)removeTask:(CLTaskFactory *)task
{
// remove the item for the deleted row from the store
[allTasks removeObjectIdenticalTo:task];
NSInteger taskCount = [allTasks count];
NSLog(#"Removed: %#, there are now %d remaining tasks, they are:", task, taskCount);
for (int i = 0; i < taskCount; i++) {
NSLog(#"%#, status: %#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:i], [[[[CLTaskStore sharedStore] allTasks] objectAtIndex:i] didComplete]?#"YES":#"NO");
}
}
- (void)moveTaskAtIndex:(int)from toIndex:(int)to
{
if (from == to) {
return;
}
CLTaskFactory *task = [allTasks objectAtIndex:from];
[allTasks removeObjectAtIndex:from];
[allTasks insertObject:task atIndex:to];
}
#end
Thanks for your help!
The table view seems to be reusing the dequeued cell
That's exactly what it does; it reuses cells whenever possible. If you had enough items to cause the table view to scroll, you'd also see the same problem.
In -tableView:cellForRowAtIndexPath: you must always set up the cell to display the correct content for the given row index, regardless of whether dequeueReusableCellWithIdentifier: returns a cell or not.
Basically:
If -dequeueReusableCellWithIdentifier: returns nil, create a new cell and add your checkbox button to it.
Then set the cell text and the button state on either this new cell or the cell returned from -dequeueReusableCellWithIdentifier:
Darren is correct. If you look at your code here:
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;
}
your only setting up the cell if(cell == nil)
Change your code to
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;

Resources