How to show different alerts without using delegate in iOS? - ios6

i have created an image view which was added to a button, i.e.) set of images were added to the image view which the array was added to the loop and same for the button, image were centered and paging were enabled, so images were now appears in a sequence with button on it , these were added to the scorllview while scrolling is enabled and by selecting each image an alert should appear like first image, second image,etc. My question is: but the alert should appears differently without using alert view delegate, how to show different alert by selecting on each image?
int buttonXPostion = 0;
for(int i = 0; i < [_array count]; i++)
{
buttonXPostion = i*frameWidth;
wallPaperButton = [[UIButton alloc] initWithFrame:CGRectMake(buttonXPostion,7,frameWidth, frameheight)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,frameWidth,frameheight)];
imageView.contentMode = UIViewContentModeCenter;
imageView.image=[UIImage imageNamed:[_array objectAtIndex:i]];
[wallPaperButton addTarget:self action:#selector(imageSelected:) forControlEvents:UIControlEventTouchUpInside];
[wallPaperButton addSubview:imageView];
[scrollImage addSubview:wallPaperButton];
}

Try this code may be this will help you..
-(IBAction)imageSelected:(id)sender
{
if(sender.tag==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"First Image Button Pressed." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag=sender.tag;
}
else if(sender.tag==1)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"Second Image Button Pressed." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag=sender.tag;
}
........ /// implement if condition as per tag you require
}

ya i have got done! By setting tag for the button,
wallPaperButton.tag=i;
-(IBAction)imageSelected:(id)sender
{
UIButton *button = sender;
switch (button.tag) {
case 0:{
NSString *message=#"FirstImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
case 1:{
NSString *message=#"SecondImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
case 2:{
NSString *message=#"ThirdImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
case 3:{
NSString *message=#"FourthImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
case 4:{
NSString *message=#"FifthImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
case 5:{
NSString *message=#"sixthImage";
alert=[[UIAlertView alloc]initWithTitle:#"" message:message delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
break;}
default:
break;
}
[alert show];
}

Related

Strange AlertView Behavior

This is what is happening....
I am making a game where by the end of the challenge a customized UIAlert shows saying if the player wins or loses. The problem is... that message is displaying twice and I have no idea why....
-(void)checkOnTests{
int p1sc;
int p1t;
int p2sc;
int p2t;
// IN BETWEEN, SCORES ARE CHECKED AND THEY ARE FINE
if (p1sc > p2sc) {
NSLog(#"P1 Wins");
winnerIndex = 1; // (INT)
if (playerIndex == winnerIndex) {
self.lbl_plyer_score.textColor = [UIColor greenColor]; //WINS
self.lbl_opponent_score.textColor = [UIColor redColor]; //LOSES
[self finishChallengeWherePlayer:YES amtOfGold:2];
}else{
self.lbl_plyer_score.textColor = [UIColor redColor];
self.lbl_opponent_score.textColor = [UIColor greenColor];
[self finishChallengeWherePlayer:NO amtOfGold:0];
}
}else if (p1sc < p2sc){
winnerIndex = 2;
NSLog(#"P2 Wins");
if (playerIndex == winnerIndex) {
self.lbl_plyer_score.textColor = [UIColor greenColor];
self.lbl_opponent_score.textColor = [UIColor redColor];
[self finishChallengeWherePlayer:YES amtOfGold:2];
}else{
self.lbl_plyer_score.textColor = [UIColor redColor];
self.lbl_opponent_score.textColor = [UIColor greenColor];
[self finishChallengeWherePlayer:NO amtOfGold:0];
}
}else if (p1sc == p2sc){
NSLog(#"We got a tie match");
winnerIndex = 3;
if (((p1t == 0) && (p2t == 0)) || (p1t == p2t)) {
[self finishChallengeWherePlayer:YES amtOfGold:1];
}else if (p1t < p2t){
[self finishChallengeWherePlayer:YES amtOfGold:2];
}else if (p1t > p2t){
[self finishChallengeWherePlayer:YES amtOfGold:1];
}
}
}
The code above checks on results. So far everything is correct. No errors.
Below I implement the code where the message displays to the player telling if they win or lose the challenge.
-(void)finishChallengeWherePlayer:(BOOL)wins amtOfGold:(int)amt {
NSString *endMsg;
if (wins) {
endMsg = [NSString stringWithFormat:#"Congrats! You win the challenge, gaining: %i gold", amt];
}else{
endMsg = [NSString stringWithFormat:#"Oh No! You have lost the challenge. No gold for you"];
}
GameAlert *alert = [[GameAlert alloc] initWithTitle:#"Results" message:endMsg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show]; // this is my custom UIAlertView that is working fine throughout the game.
[self.delegate challengeFinished:amt testname:linker];
}
The only thing that This view controller is doing differently from the rest of the game is in the box below:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
[self dismissViewControllerAnimated:YES completion:nil];
}
My question is... Do I really have to tell the delegate that the challenge is over only after i dismiss this ViewController or am I doing something wrong here ? The alert is showing twice and I feel like a fool :(

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.

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

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

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