Is there a way select a specific image for use in a UITable iOS? - ios6

I have a UITable, and I like to add an image in the detail view for a cell. I can handle the selection for any image from the camera roll or from the camera:
cell.imageView.image = someImage;
But how do I define a specific image - in the case above: "someImage", so that the next time the app is run, the correct image is shown for each item.
UPDATE. This is the code I'm using to snap/select an image..
- (IBAction)btnTakePicture_Clicked:(id)sender
{
NSLog(#"%s", __FUNCTION__);
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Select Image from..." delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Camera", #"Image Gallary", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.alpha=0.90;
actionSheet.tag = 1;
[actionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(#"%s", __FUNCTION__);
switch (actionSheet.tag)
{
case 1:
switch (buttonIndex)
{
case 0:
{
#if TARGET_IPHONE_SIMULATOR
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Camera not available." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
#elif TARGET_OS_IPHONE
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
//picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
#endif
}
break;
case 1:
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
break;
}
break;
default:
break;
}
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
NSLog(#"%s", __FUNCTION__);
dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
imgPicture.image = [[UIImage alloc] initWithData:dataImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
UPDATE 2. With the help from people below, I think this solution will work for me:
- (IBAction)photoLibraryAction:(id)sender
{
int c = self.capturedImages.count;
for (int i=0; i < c; i++ ){
if (self.imageView.tag == cellTag) {
NSLog(#"found it");
} else {
NSLog(#"can't find it");
}
}
}
if ([self.capturedImages count] == 1)
{
// we took a single shot
[self.imageView setImage:[self.capturedImages objectAtIndex:0]];
[self.imageView setTag:myTag];
}

I would do in this way.
#interface CustomClassCell : UITableViewCell
#property (unsafe_unretained, nonatomic) IBOutlet UIImageView *HomePicture;
#end
#interface CustomClass : NSObject
#property (nonatomic, copy) NSString *PicPath;
#end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomClassCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CustomClassCellIdentifer"];
id object = [self.tableData objectAtIndex:indexPath.row];
CustomClass *myObject = (CustomClass*)object;
cell.HomePicture.image = [UIImage imageNamed:myObject.PicPath];
return cell;
}

Related

iOS 6 peripheral disconnect immediately after connected

OK, I'm using Core Bluetooth to connect my i-Pad to another BLE sensor.
I scan and detect it easily but when I want to establish a connection, the "did connect peripheral" method is only called during 30 sec as if I've called a disconnection...
And this result stay the same even I select or deselect "App Communicates using CoreBluetooth" in Required background mode.
- (id) init
{
self = [super init];
if (self)
{
pendingInit = YES;
centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
foundPeripherals = [[NSMutableArray alloc] init];
connectedServices = [[NSMutableArray alloc] init];
}
return self;
}
- (void) centralManagerDidUpdateState:(CBCentralManager *)central
{
static CBCentralManagerState previousState = -1;
switch ([centralManager state])
{
case CBCentralManagerStateUnsupported:
{
NSLog(#"NSCentralManager State Unsupported...");
break;
}
case CBCentralManagerStatePoweredOff:
{
NSLog(#"NSCentralManager State Powered OFF");
[self clearDevices];
[discoverPeripheralDelegate discoveryDidRefresh];
if (previousState != -1)
{
[discoverPeripheralDelegate discoveryStatePoweredOff];
}
break;
}
case CBCentralManagerStateUnauthorized:
{
NSLog(#"NSCentralManager State Unauthorized: the application is not allowed");
break;
}
case CBCentralManagerStateUnknown:
{
NSLog(#"NSCentralManager state unknown... Bad News...");
break;
}
case CBCentralManagerStatePoweredOn:
{
NSLog(#"NSCentralManager State Powered ON!");
pendingInit = NO;
[self loadSavedDevices];
[centralManager retrieveConnectedPeripherals];
[discoverPeripheralDelegate discoveryDidRefresh];
break;
}
case CBCentralManagerStateResetting:
{
NSLog(#"CBCentralManager State Resetting");
[self clearDevices];
[discoverPeripheralDelegate discoveryDidRefresh];
[peripheralDelegate alarmServiceDidReset];
pendingInit = YES;
break;
}
}
previousState = [centralManager state];
}
- (void) loadSavedDevices
{
storedDevices = [[NSArray alloc] initWithObjects:kPressureServiceUUIDString, nil];
for (id deviceUUIDString in storedDevices) {
if (![deviceUUIDString isKindOfClass:[NSString class]])
continue;
CFUUIDRef uuid = CFUUIDCreateFromString(NULL, (CFStringRef)deviceUUIDString);
if (!uuid)
continue;
storedUUIDs = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"StoredUUIDS"]];
for (int i = 0; i < storedUUIDs.count; i++) {
NSArray * tempStoredUUIDs = storedUUIDs[i];
storedUUIDs[i] = [tempStoredUUIDs mutableCopy];
}
[centralManager scanForPeripheralsWithServices:nil options:nil];
storedUUIDs = [[NSMutableArray alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:storedUUIDs forKey:#"StoredUUIDS"];
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSString * finaluuids = [NSString stringWithFormat:#"%#",peripheral.UUID];
if (storedUUIDs.count == 0)
{
storedUUIDs = [[NSMutableArray alloc] initWithObjects:finaluuids, nil];
[centralManager stopScan];
[centralManager connectPeripheral:peripheral options:nil];
}
}
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(#"connected");
}
Here is my console. I don't have any warning, any error or deallocating just:
2013-05-14 09:21:14.925 PRESSURE[262:907] connected
2013-05-14 09:21:14.927 PRESSURE[262:907] Service (Sensor) connected
2013-05-14 09:21:44.994 PRESSURE[262:907] Service (Sensor) disconnected
How can I avoid my peripheral disconnected immediately after connection please?
It drives me crazy!
You have to do [peripheral retain] on didDiscoverPeripheral or put it into the retain property.
It is released right after the connect by BLE framework.

Scrolling TableView effects response time of SegmentControl

This may be a strange problem and I hope someone has had it before.
I added a SegmentControl to my TableView using this code:
UIView *headerView = [[UIView alloc] init ];
[headerView addSubview:resultsSegment];
self.tableView.tableHeaderView = headerView;
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
With help from these forums the first three lines made the Segment part of the TableView Header so that it stayed in place for scrolling. Great.
However, that disabled the ability to click on the SegmentControl.
Adding the last line made that possible again.
The SegmentControl performs great UNTIL scrolling, then it becomes really unresponsive. It doesn't throw up any errors and it does eventually accept a press from the finger, but you have to tap it 5/6 times before it switches.
If anyone can shed some light on this that would be amazing
Any extra information you need I'll be happy to provide!
EDIT ----
ViewController.h
#interface StdTCPTestViewController : UIViewController <UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate> {
NSTimer *Timer;
}
#property (nonatomic, strong) NSString *typeOfTest;
#property (nonatomic, strong) NSString *testLocation;
#property (nonatomic, strong) NSString *statusText;
#property (nonatomic, strong) NSString *showResultType;
#property (nonatomic, assign) NSInteger *progressInt;
#property (nonatomic, assign) NSString *testDirection;
#property (strong, nonatomic) IBOutlet UITextView *textView;
#property (strong, nonatomic) IBOutlet UIProgressView *testProgressBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSArray *ResultTitles;
#property (nonatomic, retain) NSMutableArray *downloadResults;
#property (nonatomic, retain) NSMutableArray *uploadResults;
#property (strong, nonatomic) IBOutlet UISegmentedControl *resultsSegment;
- (IBAction)resultsSwitch:(id)sender;
Select areas of ViewController.m
- (void)viewDidLoad
{
[resultsSegment setTitle:#"Download" forSegmentAtIndex:0]; // Sets the title for the 1st segment button
[resultsSegment setTitle:#"Upload" forSegmentAtIndex:1]; // Sets the title for the 2nd segment button
[super viewDidLoad];
// UIView *headerView = [[UIView alloc] init ];
// [headerView addSubview:resultsSegment];
// self.tableView.tableHeaderView = headerView;
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
[self APISimpleDemo];
self.navigationItem.title = typeOfTest; // Set viewcontroller title to the type of test it is
}
- (IBAction)resultsSwitch:(id)sender {
if([sender selectedSegmentIndex] == 0){
showResultType = #"download";
[self.tableView reloadData];
}
else {
showResultType = #"upload";
[self.tableView reloadData];
}
}
#pragma mark Table Definitions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // Default is 1 if not implemented
{
return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return #"";
break;
case 1:
return #"";
break;
case 2:
return #"";
break;
default:
return #"Section Count Error";
break;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return 10;
break;
case 1:
return 22;
break;
case 2:
return 0;
break;
default:
return 22;
break;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
switch (section) {
case 0:
return 3;
break;
case 1:
return 0;
break;
case 2:
return [ResultTitles count];
break;
default:
return 0;
break;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *serverLoc = [tableView dequeueReusableCellWithIdentifier:#"speedCell"];
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
serverLoc.textLabel.text = #"Test location:";
serverLoc.detailTextLabel.text = testLocation;
break;
case 1:
serverLoc.textLabel.text = #"Status:";
serverLoc.detailTextLabel.text = statusText;
break;
case 2:
serverLoc.textLabel.text = #"Progress";
serverLoc.detailTextLabel.text = [NSString stringWithFormat:#"%ld%%", (long)progressInt];
break;
}
break;
case 2:
if ([showResultType isEqual:#"download"]) {
serverLoc.textLabel.text = [self.ResultTitles objectAtIndex:indexPath.row];
serverLoc.detailTextLabel.text = [self.downloadResults objectAtIndex:indexPath.row];
break;
}
else {
serverLoc.textLabel.text = [self.ResultTitles objectAtIndex:indexPath.row];
serverLoc.detailTextLabel.text = [self.uploadResults objectAtIndex:indexPath.row];
break;
}
break;
default:
break;
}
return serverLoc;
}
The likely problem here is that you have a single segmentControl but you added it as a subview to both the tableHeaderView and the tableView.
I solved the problem of an unresponsive SegmentControl upon scrolling by moving the code below from the viewDidLoad method to the titleForHeaderInSection
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
It now looks like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return #"";
break;
case 1:
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
return #"";
break;
case 2:
return #"";
break;
default:
return #"Section Count Error";
break;
}
}

by Adding Polyline(path) on MKMapview crashing the app in ios6

I have a requirement to adding a path in my MKMapview between two annotation pin. There is no issue with ios 5 or older but when i try to run app in ios 6 app is surprisingly quit. below is my code. If there is any correction in my code then please suggest me.
1.So my question is suggest the best way how to decrees memory in my following code so that i can solve crash in my Application.
- (void)viewDidLoad
{
NVPolylineAnnotation *annotation = [[NVPolylineAnnotation alloc] initWithPoints:pathArray mapView:_mapView];
[_mapView addAnnotation:annotation];
[annotation release];
[pathArray removeAllObjects];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"%s",__FUNCTION__);
if ([annotation isKindOfClass:[NVPolylineAnnotation class]])
{
NSLog(#"=========ANOTATION=========NVPolylineAnnotationView START");
//ann=[ann initWithAnnotation:annotation mapView:_mapView];
NVPolylineAnnotationView *ann=[[NVPolylineAnnotationView alloc] init];
return [[ann initWithAnnotation:annotation mapView:_mapView] autorelease];//[[[NVPolylineAnnotationView alloc] initWithAnnotation:annotation mapView:_mapView] autorelease];
}
else if([annotation isKindOfClass:[MapViewAnnotation class]])
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"pointers"] ;
// annView.rightCalloutAccessoryView = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
annView.animatesDrop=NO;
annView.canShowCallout = TRUE;
return [annView autorelease];
}
else if([annotation isKindOfClass:[PlacePin class]])
{
{
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
else {
[mapView.userLocation setTitle:#"I am here"];
}
return pinView;
}
}
return nil;
}
- (void) mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(#"%s",__FUNCTION__);
// fixes that some marker are behind the polyline
for (int i=0; i<[views count]; i++)
{
MKAnnotationView *view = [views objectAtIndex:i];
if ([view isKindOfClass:[NVPolylineAnnotationView class]])
{
[[view superview] sendSubviewToBack:view];
/* In iOS version above 4.0 we need to update the polyline view after it
has been added to the mapview and it ready to be displayed. */
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
{
[self updatePolylineAnnotationView];
}
}
}
NSLog(#"----------didAddAnnotationViews");
}
- (void)updatePolylineAnnotationView
{
NSLog(#"%s",__FUNCTION__);
MKAnnotationView *annotationView = [views objectAtIndex:0];
id <MKAnnotation> mp = [annotationView annotation];
[mapView selectAnnotation:mp animated:NO];
*/
for (NSObject *a in [_mapView annotations])
{
if ([a isKindOfClass:[NVPolylineAnnotation class]])
{
NVPolylineAnnotation *polyline = (NVPolylineAnnotation *)a;
NSObject *pv = (NSObject *)[_mapView viewForAnnotation:polyline];
if ([pv isKindOfClass:[NVPolylineAnnotationView class]])
{
NVPolylineAnnotationView *polylineView =
(NVPolylineAnnotationView *)[_mapView viewForAnnotation:polyline];
[polylineView regionChanged];
}
}
}
}

Search bar and search display controller with segue

Never called when a search table cell is tapped
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Show Detail"])
{
Player *player = [self.fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]];
[segue.destinationViewController setPlayer:player];
}
}
This filters the list correctly, but the prepareForSegue is never called when a search table cell is tapped.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Player Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.tableView)
{
// normal table view population
Player *player = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
else if(tableView == self.searchDisplayController.searchResultsTableView)
{
// search view population
Player *player = [self.filteredFetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
return cell;
}
you need to put IF that check if the search have results.
like in this code:
if ([[segue identifier]isEqualToString:#"ShowDetails"])
{
ShowDetailsViewController *sdvc = (ShowDetailsViewController *)[segue destinationViewController];
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
Books *selectedBooks = nil;
if(self.searchDisplayController.active)
selectedBooks = (Books *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
else
selectedBooks = (Books *)[[self fetchResultsController] objectAtIndexPath:indexPath];
sdvc.currentBooks = selectedBooks;
}

Custom swipe function in UITableViewCell doesn't work

I need to add the count in the uitableviewcell in a such a way that when I trigger the swipe function the count should be incremented in the corresponding cell and while tapping the count should be decremented.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
NSString *CellIdentifier = #"sample";
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
UISwipeGestureRecognizer *recognizer;
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapFrom:)];
[self addGestureRecognizer:recognizer];
self.tapRecognizer = (UITapGestureRecognizer *)recognizer;
recognizer.delegate = self;
[recognizer release];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
[self addGestureRecognizer:recognizer];
[recognizer release];
UILabel *cookieLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,5, 120,30)];
cookieLabel.text = #"hello";
cookieLabel.font = [UIFont systemFontOfSize:15.0f];
cookieLabel.textColor = [UIColor blackColor];
cookieLabel.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:cookieLabel];
[cookieLabel release];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
costLabel = [[UILabel alloc] initWithFrame:CGRectMake( 200, 5, 230, 30)];
//costLabel.text = handleSwipeFrom:;
costLabel.font = [UIFont systemFontOfSize:15.0f];
costLabel.textColor = [UIColor blackColor];
costLabel.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:costLabel];
[costLabel release];
[self setUserInteractionEnabled:YES];
return cell;
}
Don't add the UISwipeGestureRecognizer to the cell. Add it to the UITableView.
I used TISwipeableTableView as a base and modified it heavily to work correctly (they did their own touch handling, which resulted in a "weird, unnative" feeling)
- (void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint swipeLocation = [gestureRecognizer locationInView:self];
NSIndexPath *swipedIndexPath = [self indexPathForRowAtPoint:swipeLocation];
TISwipeableTableViewCell* swipedCell = (TISwipeableTableViewCell *)[self cellForRowAtIndexPath:swipedIndexPath];
if ([swipedCell isKindOfClass:[TISwipeableTableViewCell class]]) {
if (![swipedIndexPath isEqual:indexOfVisibleBackView]) {
[self hideVisibleBackView:YES];
[swipedCell revealBackView];
[self setIndexOfVisibleBackView:swipedIndexPath];
if (swipeDelegate && [swipeDelegate respondsToSelector:#selector(tableView:didSwipeCellAtIndexPath:)]){
[swipeDelegate tableView:self didSwipeCellAtIndexPath:[self indexPathForRowAtPoint:swipeLocation]];
}
}
}
}
}
}
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
if ((self = [super initWithFrame:frame style:style])) {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
UIGestureRecognizer *swipeGesture = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(didSwipe:)] autorelease];
[self addGestureRecognizer:swipeGesture];
}
}
return self;
}
This should get you started.
[cell addGestureRecognizer:recognizer]

Resources