I've a problem with Annotation when clicked and send data to "Prepare to segue"
I've used this code:
- (void)viewDidLoad {
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:#"Ristoranti"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error)
{
NSLog(#"QUERY -----> :%#", objects);
for(NSMutableDictionary *note1 in objects) {
float realLatitude1 = [[note1 objectForKey:#"Latitudine"] floatValue];
float realLongitude1 = [[note1 objectForKey:#"Longitudine"] floatValue];
NSLog(#"(PARSE) Latitudine: %f", realLatitude1);
NSLog(#"(PARSE) Longitudine: %f", realLongitude1);
DisplayMap *displayMap = [[DisplayMap alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude1;
theCoordinate.longitude = realLongitude1;
displayMap.coordinate = theCoordinate;
displayMap.title = [note1 objectForKey:#"NomeLocale"];
displayMap.subtitle = [note1 objectForKey:#"Indirizzo"];
displayMap.icon = [note1 objectForKey:#"PinMappa"];
[_mapView setDelegate:self];
[_mapView addAnnotation:displayMap];
}
}
}];
}
and:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (![annotation isKindOfClass:[DisplayMap class]])
{
return nil;
}
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (pinView == nil)
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.canShowCallout = YES;
}
else
pinView.annotation = annotation;
DisplayMap *myAnn = (DisplayMap *)annotation;
pinView.image = [UIImage imageNamed:myAnn.icon];
// Create a UIButton object to add on the
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[pinView setRightCalloutAccessoryView:rightButton];
return pinView;
}
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
if ([(UIButton*)control buttonType] == UIButtonTypeDetailDisclosure)
{
NSLog(#"The annotation tapped is: %#", view.annotation.title);
NSUInteger index = [mapView.annotations indexOfObject:view.annotation];
NSLog(#"%lu", (unsigned long)index);
//[self performSegueWithIdentifier:#"Prova" sender:self];
}
}
and:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"Prova"]) {
DettagliAlberghi *destViewController = segue.destinationViewController;
DisplayMap *displayMap = [[DisplayMap alloc] init];
displayMap.title = [note1 objectForKey:#"NomeLocale"];
displayMap.subtitle = [note1 objectForKey:#"Indirizzo"];
displayMap.icon = [note1 objectForKey:#"PinMappa"];
displayMap.Telefono = [note1 objectForKey:#"Telefono"];
displayMap.Email = [note1 objectForKey:#"Email"];
displayMap.Sito = [note1 objectForKey:#"Sito"];
displayMap.TipologiaLocale = [note1 objectForKey:#"TipologiaLocale"];
displayMap.Cucina = [note1 objectForKey:#"Cucina"];
displayMap.Vegano = [note1 objectForKey:#"Vegano"];
displayMap.Valutazione = [note1 objectForKey:#"Valutazione"];
displayMap.Latitudine = [note1 objectForKey:#"Latitudine"];
displayMap.Longitudine = [note1 objectForKey:#"Longitudine"];
displayMap.Anteprima1 = [note1 objectForKey:#"Anteprima1"];
displayMap.Anteprima2 = [note1 objectForKey:#"Anteprima2"];
displayMap.Anteprima3 = [note1 objectForKey:#"Anteprima3"];
displayMap.FaceB = [note1 objectForKey:#"Facebook"];
displayMap.Twit = [note1 objectForKey:#"Twitter"];
NSLog(#"Dettagli Ristorante: \n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#", displayMap.title, displayMap.subtitle, displayMap.Telefono, displayMap.Email, displayMap.Sito, displayMap.TipologiaLocale, displayMap.Cucina, displayMap.Vegano, displayMap.Valutazione, displayMap.Latitudine, displayMap.Longitudine, displayMap.Anteprima1, displayMap.Anteprima2, displayMap.Anteprima3, displayMap.FaceB, displayMap.Twit);
destViewController.recipes = displayMap;
}
}
I would like to understand how to recognize some annotation is pressed and send the data to the next page through "PrepareForSegue".
Does anyone know how to help me? I'm going crazy.
Thanks in advance.
You will simply want to use the mapView:didSelectAnnotationView: delegate call.
https://developer.apple.com/documentation/mapkit/mkmapviewdelegate/1452393-mapview
From in mapView:didSelectAnnotationView, call the segue call via the performSegueWithIdentifier.
[self performSegueWithIdentifier:#"Prova" sender:self];
Assuming you setup "note1" from within mapView:didSelectAnnotationView based on the annotation selected.
Related
How can I change this UITableViewController custom class to dynamically change the height of the Table View Cells? I have specified different font sizes for the iPad and iPhone size classes.
(This is a continuation of a previous discussion with #rdelmar)
#import "CREWFoodWaterList.h"
#interface CREWFoodWaterList ()
#end
#implementation CREWFoodWaterList
#define VIEW_NAME #"FoodWaterList" // add to database for this view and notes view
#define VIEW_DESCRIPTION #"Food Water - items to keep available" // to add to the database
#define RETURN_NC #"NCSuggestedContentsMenu" // where to return to when complete processing should be specified there
#define NOTES_TITLE #"Food and Water Notes" // pass to notes VC
#define THIS_NC #"NCFoodWaterList" // pass to next VC (so returns to the NC for this view)
- (IBAction)changedSwitch:(UISwitch *)sender {
if (sender.tag == 0) {
[self saveSwitch: #"switchWater" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 1) {
[self saveSwitch: #"switchCanned" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 2) {
[self saveSwitch: #"switchComfort" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 3) {
[self saveSwitch: #"switchSpecial" toValue:[NSNumber numberWithBool:sender.on]];
}
} // end of changedSwitch
-(void)loadSavedSwitches {
// now set the switches to previously stored values
NSNumber *switchValue;
switchValue = [self getSwitch: #"switchWater"];
if ([switchValue intValue] == 0) {
self.switchWater.on = NO;
} else {
self.switchWater.on = YES;
}
self.textWater.text = [self getDescription:#"switchWater"];
switchValue = [self getSwitch: #"switchCanned"];
if ([switchValue intValue] == 0) {
self.switchCanned.on = NO;
} else {
self.switchCanned.on = YES;
}
self.textCanned.text = [self getDescription:#"switchCanned"];
switchValue = [self getSwitch: #"switchComfort"];
if ([switchValue intValue] == 0) {
self.switchComfort.on = NO;
} else {
self.switchComfort.on = YES;
}
self.textComfort.text = [self getDescription:#"switchComfort"];
// self.textComfort.textColor = [UIColor whiteColor];
switchValue = [self getSwitch: #"switchSpecial"];
if ([switchValue intValue] == 0) {
self.switchSpecial.on = NO;
} else {
self.switchSpecial.on = YES;
}
self.textSpecial.text = [self getDescription:#"switchSpecial"];
}
- (void) createNewSwitches {
// set create all switches and set to off
[self newSwitch: #"switchWater" toValue:#"At least three litres of bottle water per person per day"];
[self newSwitch: #"switchCanned" toValue:#"Canned foods, dried goods and staples"];
[self newSwitch: #"switchComfort" toValue:#"Comfort foods"];
[self newSwitch: #"switchSpecial" toValue:#"Food for infants, seniors and special diets"];
}
// COMMON Methods
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// set font size for table headers
[[UIDevice currentDevice] model];
NSString *myModel = [[UIDevice currentDevice] model];
NSInteger nWords = 1;
NSRange wordRange = NSMakeRange(0, nWords);
NSArray *firstWord = [[myModel componentsSeparatedByString:#" "] subarrayWithRange:wordRange];
NSString *obj = [firstWord objectAtIndex:0];
if ([obj isEqualToString:#"iPad"]) {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:26]];}
else if ([obj isEqualToString:#"iPhone"]) {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:16]];
};
[defaults setObject:NOTES_TITLE forKey: #"VCtitle"]; // pass to notes VC
[defaults setObject:VIEW_NAME forKey: #"VCname"]; // pass to notes VC to use to store notes
[defaults setObject:THIS_NC forKey: #"CallingNC"]; // get previous CallingNC and save it for use to return to in doneAction
[self initializeView];
} // end of viewDidLoad
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.tableView reloadData]; // this was necessary to have the cells size correctly when the table view first appeared
}
- (void) initializeView {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"View" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#)", VIEW_NAME];
[request setPredicate:pred];
NSError *error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) { // create new view instance
NSManagedObject * newView;
newView = [NSEntityDescription insertNewObjectForEntityForName:#"View" inManagedObjectContext:context];
[newView setValue:VIEW_NAME forKey:#"viewName"];
[newView setValue:VIEW_DESCRIPTION forKey:#"viewDescription"];
// create all switches and set to off
[self createNewSwitches];
}
// load all switches
[self loadSavedSwitches];
} // end of initializeView
// create a new switch
- (void) newSwitch:(NSString*)switchName toValue:(NSString*)switchDescription {
NSError *error = nil;
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject * newSwitch;
newSwitch = [NSEntityDescription insertNewObjectForEntityForName:#"Switch" inManagedObjectContext:context];
[newSwitch setValue:VIEW_NAME forKey:#"viewName"];
[newSwitch setValue:switchName forKey:#"switchName"];
[newSwitch setValue:switchDescription forKey:#"switchDescription"];
[newSwitch setValue:[NSNumber numberWithInt:0] forKey:#"switchValue"];
if (! [context save:&error])
// NSLog(#"**** START entering %#",VIEW_NAME);
NSLog(#"newSwitch Couldn't save new data! Error:%#", [error description]);
} // end of newSwitch
// read existing switch settings
- (NSNumber *) getSwitch:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName];
[request setPredicate:pred];
// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
};
NSNumber *switchValue;
if (! [objects count] == 0) {
matches = objects [0];
switchValue = [matches valueForKey : #"switchValue"];
}
return switchValue;
} // end of getSwitch
- (NSString *) getDescription:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName];
[request setPredicate:pred];
// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
// NSLog(#"**** START entering %#",VIEW_NAME);(#"getSwitch Fetch error:%#", fetchError); // no
};
NSString *switchDescription;
if (! [objects count] == 0) {
matches = objects [0];
switchDescription = [matches valueForKey : #"switchDescription"];
}
return switchDescription;
} // end of getDescription
- (void)saveSwitch:(NSString*)switchName toValue:(NSNumber*)newSwitchValue {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context]; // get switch entity
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName ];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *fetchError = nil;
NSArray * objects = [context executeFetchRequest:request error:&fetchError];
if (![objects count] == 0) {
matches = objects[0];
}
[matches setValue:newSwitchValue forKey:#"switchValue"];
if (! [context save:&fetchError])
// NSLog(#"**** START entering %#",VIEW_NAME);
NSLog(#"saveSwitch Couldn't save data! Error:%#", [fetchError description]); // perhaps this can be Done later
} // end of saveSwitch
// set alternate cells to different colors
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
// Helper method..
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:#"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *grayishCyan = #"#a3c9ca";
NSString *grayishRed = #"#caa4a3";
UIColor *colorCyan = [self getUIColorObjectFromHexString:grayishCyan alpha:.9];
UIColor *colorPink = [self getUIColorObjectFromHexString:grayishRed alpha:.9];
// // NSLog(#"**** START entering %#",VIEW_NAME);(#"UIColor: %#", colorPink);
if (indexPath.row == 0 || indexPath.row%2 == 0) {
cell.backgroundColor = colorCyan;
}
else {
cell.backgroundColor = colorPink;
}
}
- (IBAction)doneAction:(id)sender {
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
UIViewController *viewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:RETURN_NC]; // previous Navigation controller
[self presentViewController:viewController animated:YES completion:nil];
};
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
I'm running a MKLocalSearch request and when I find POIs I want to drop a pin based on the coordinates of the POIs I find. NSLog(#"annotations %d",[mapView.annotations count]); returns 0 even with valid coordinates for the POIs
- (void)resultsForButtonTapped:(NSString *)search
{
arrayOfPOIs = [[NSMutableArray alloc] init];
arrayOfAnnotaions = [[NSMutableArray alloc] init];
NSLog(#"%#",search);
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
MKCoordinateRegion region;
request.naturalLanguageQuery = search;
request.region = region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localsearch = [[MKLocalSearch alloc] initWithRequest:request];
[localsearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error != nil) {
return;
}else{
if ([response.mapItems count] == 0) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
for (MKMapItem *item in response.mapItems)
{
NSString *name = item.name;
NSLog(#"%#",name);
[arrayOfPOIs addObject:name];
}
results = response;
NSLog(#"%d",[arrayOfPOIs count]);
for (int i=0; i<[results.mapItems count]; i++) {
MKMapItem* itemPOI = results.mapItems[i];
NSLog(#"Result: %#",itemPOI.placemark.name);
NSLog(#"Result: %#",itemPOI.placemark.name);
MKPlacemark* annotation= [[MKPlacemark alloc] initWithPlacemark:itemPOI.placemark];
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = annotation.coordinate;
[mapView addAnnotation:marker];
NSLog(#"annotations %d",[mapView.annotations count]);
}
[self loadTheDataAgain];
}
}];
// NSLog(#"outside the block, the count is %lu",(unsigned long)[arrayOfPOIs count]);
NSLog(#"stuff %#",arrayOfAnnotaions);
}
I am trying to find a way to make multiple annotation disclosure buttons open other views.
For example, annotation1 disclosure button needs to open ViewController 1.xib, annotation2 needs to open ViewController2.xib, and so on. Is this possible?
I've got this code so far, which sets the location according to coordinates, and sets the user location.
- (void)viewDidLoad
{
[super viewDidLoad];
_mapView.showsUserLocation = YES;
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = 40.714353;
annotationCoord.longitude = -74.005973;
coord = 1;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = #"New York";
[_mapView addAnnotation:annotationPoint];
CLLocationCoordinate2D annotationCoord1;
annotationCoord1.latitude = 51.511214;
annotationCoord1.longitude = -0.119824;
coord = 2;
MKPointAnnotation *annotationPoint1 = [[MKPointAnnotation alloc] init];
annotationPoint1.coordinate = annotationCoord1;
annotationPoint1.title = #"London";
[_mapView addAnnotation:annotationPoint1];
}
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *mapPin = nil;
if(annotation != map.userLocation)
{
static NSString *defaultPinID = #"defaultPin";
mapPin = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if (mapPin == nil )
{
mapPin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:defaultPinID] autorelease];
mapPin.canShowCallout = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
mapPin.rightCalloutAccessoryView = infoButton;
}
else
mapPin.annotation = annotation;
}
return mapPin;
}
What do I put into here:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
// ???
}
All help is appreciated. Thanks
You could do something like this,
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
if ([view.annotation.title isEqualToString:#"The titel of your annotation"])
{
// Do something
}
}
I can't imagine why it doesn't works..
I want change pin color, and use some other things that this method offers, but it just doesn't work.
Maybe im using this method wrong?
Example would be best, thank you.
[mapView setMapType: MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
for (NSDictionary *dict in self.klubiArray3) {
double latid = [[dict valueForKey:#"LatiS"] doubleValue];
double longid =[[dict valueForKey:#"LongiS"] doubleValue];
MKCoordinateRegion region = {{0.0, 0.0}, {0.0, 0.0}};
region.span.latitudeDelta = 0.005;
region.span.longitudeDelta = 0.005;
region.center.latitude = latid;
region.center.longitude = longid;
[mapView setRegion:region animated:YES];
NewClass *ann = [[NewClass alloc] init];
ann.title = [dict valueForKey:#"AnnotM"];
ann.subtitle = [dict valueForKey:#"Adress"];;
ann.coordinate = region.center;
[mapView addAnnotation:ann ];
}
}
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"Controll comes here");
if (annotation == mapView.userLocation)
return nil;
MKPinAnnotationView *pin = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier: #"asdf"];
if (pin == nil)
pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: #"asdf"] ;
else
pin.annotation = annotation;
pin.userInteractionEnabled = YES;
UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[disclosureButton setFrame:CGRectMake(0, 0, 30, 30)];
pin.rightCalloutAccessoryView = disclosureButton;
pin.pinColor = MKPinAnnotationColorPurple;
//pin.animatesDrop = YES;
[pin setEnabled:YES];
[pin setCanShowCallout:YES];
return pin;
}
Found out, i had forgotten to connect my map delegate in Interface Builder.
My class is like:
- (id)init
{
NSLog(#"lalallalalala");
if (self = [super init]) {
self.title = #"lalal";
UIImage* image = [UIImage imageNamed:#"tab.png"];
self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:self.title image:image tag:0] autorelease];
self.variableHeightRows = YES;
id<TTTableViewDataSource> ds = [MainPageDataSource dataSourceWithItems:nil];
ds.model = CreateTabModelWithCurrentSettings();
self.dataSource = ds;
}
return self;
}
- (void)loadView
{
// Create the tableview.
NSLog(#"in MainPageController");
//self.view = [[[UIView alloc] initWithFrame:TTApplicationFrame()] autorelease];
self.view =[[UIView alloc] init];
self.tableView = [[[UITableView alloc] initWithFrame:TTApplicationFrame() style:UITableViewStylePlain] autorelease];
self.tableView.rowHeight = 80.f;
self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.tableView];
}
- (id<UITableViewDelegate>)createDelegate {
return [[[TTTableViewDragRefreshDelegate alloc] initWithController:self] autorelease];
}
CreateDelegate seems not work, no drag & refresh appears. I don't know what's wrong with my code.
#aporat the view controller does extend TTTableViewController and my code changed to:
- (id)init
{
NSLog(#"lalallalalala");
if (self = [super init]) {
self.title = #"app";
UIImage* image = [UIImage imageNamed:#"tab.png"];
self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:self.title image:image tag:0] autorelease];
self.variableHeightRows = YES;
//id<TTTableViewDataSource> ds = [MainPageDataSource dataSourceWithItems:nil];
// ds.model = CreateTabModelWithCurrentSettings();
// self.dataSource = ds;
//self.dataSource = [[[MainPageDataSource alloc] init] autorelease];
}
return self;
}
- (void)createModel {
NSLog(#"in createModel");
self.dataSource = [[[MainPageDataSource alloc] init] autorelease];
}
//- (void)loadView
//{
// // Create the tableview.
//
// NSLog(#"in MainPageController");
//
// self.view = [[[UIView alloc] initWithFrame:TTApplicationFrame()] autorelease];
// //self.view =[[UIView alloc] init];
// self.tableView = [[[UITableView alloc] initWithFrame:TTApplicationFrame() style:UITableViewStylePlain] autorelease];
// self.toolbarItems = [NSArray arrayWithObjects:
// [TTButton buttonWithStyle:#"toolbarButton:" title:#"Toolbar Button"],
// [TTButton buttonWithStyle:#"toolbarRoundButton:" title:#"Round Button"],
// nil];
//
// self.tableView.rowHeight = 80.f;
// self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// [self.view addSubview:self.tableView];
//
//
//}
//- (void)viewDidLoad {
// [super viewDidLoad];
//
// self.navigationController.navigationBar.alpha = 0;
//}
- (id<UITableViewDelegate>)createDelegate {
return [[[TTTableViewDragRefreshDelegate alloc] initWithController:self] autorelease];
}
Still not appears drag & fresh
There are a few issues with your code:
Your view controller has to extend TTTableViewController
Don't override self.view & self.tableView in loadView. The TTTableViewController load these views for you.
Create your datasource using the standard method. This function is called automatically if you're using TTTableViewController:
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)createModel {
self.dataSource = [[[CurrencyDataSource alloc] init] autorelease];
}
What happens if you call this function directly? (This should manually display the drag to refresh header)
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)reload {
if ([self.tableView.delegate isKindOfClass:[TTTableViewDragRefreshDelegate class]]) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:ttkDefaultFastTransitionDuration];
self.tableView.contentOffset = CGPointMake(0, -60.0f);
[UIView commitAnimations];
}
[super reload];
}