My switch will not reset when I call clearbtn, it just remains in the same state. Also when I call pushme and check to see if the switch is on or off it always detects its off, what would be causing this? How can I fix this? I created a Window-based application just to play around, I didnt create a UIViewController yet, is that what is causing this issue? Thank You.
My .h file
UIButton *_pushmebutton;
UITextField *_nametextfield;
UILabel *_pushmelabel;
UIImageView *_bgimage;
UISwitch *_bgswitch;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UIButton *pushmebutton;
#property (nonatomic, retain) IBOutlet UITextField *nametextfield;
#property (nonatomic, retain) IBOutlet UILabel *pushmelabel;
#property (nonatomic, retain) IBOutlet UISwitch *bgswitch;
#property (nonatomic, retain) IBOutlet UIImageView *bgimage;
- (IBAction)textFieldReturn:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
- (IBAction)pushme:(id)sender;
- (IBAction)clearbtn:(id)sender;
- (IBAction)changebg:(id)sender;
My .m File
#import "MyFirstAppAppDelegate.h"
#implementation MyFirstAppAppDelegate
#synthesize window=_window;
#synthesize pushmebutton = _pushmebutton;
#synthesize nametextfield = _nametextfield;
#synthesize pushmelabel = _pushmelabel;
#synthesize bgswitch = _bgswitch;
#synthesize bgimage = _bgimage;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application
{
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/
}
- (void)dealloc
{
[_window release];
[_pushmebutton release];
[_pushmelabel release];
[_nametextfield release];
[super dealloc];
}
-(IBAction)pushme:(id)sender
{
if([_nametextfield.text length] == 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Please Enter Your Name" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil]; [alert show]; [alert release];
}
else
{
[_nametextfield resignFirstResponder];
if(_bgimage.hidden == false)
{
self.pushmelabel.backgroundColor = [UIColor redColor];
}
if(_bgswitch.on)
{
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %# Thanks for using the App! Switch: On!", _nametextfield.text];
self.pushmelabel.text = msg;
}
else
{
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %# Thanks for using the App! Switch: Off!", _nametextfield.text];
self.pushmelabel.text = msg;
}
}
}
-(IBAction)clearbtn:(id)sender;
{
_nametextfield.text = #"";
_pushmelabel.text = #"";
_pushmelabel.backgroundColor = [UIColor clearColor];
[_bgswitch setOn:NO animated:YES];
}
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
-(IBAction)backgroundTouched:(id)sender
{
[_nametextfield resignFirstResponder];
}
-(IBAction)changebg:(id)sender
{
if(_bgimage.hidden == false)
{
_bgimage.hidden = true;
_pushmelabel.backgroundColor = [UIColor clearColor];
}
else if(_bgimage.hidden == true)
{
_bgimage.hidden = false;
if([_pushmelabel.text length] > 0)
{
_pushmelabel.backgroundColor = [UIColor redColor];
}
}
}
#end
My hunch is telling me that you haven't connected the outlet to the switch in IB. Check for that connection and make it if necessary. If the connection is already there, NSLog your switch in the pushme method and see if it comes out to nil.
You really shouldn't use ApplicationDelegate like this - it's intended to be the delegate for application events, and that is all it should be. Since it doesn't inherit from UIViewController, it wont participate in normal view lifecycle stuff, so it's very likely that is your problem. Put your view stuff in a UIViewController, and try your switch again.
Related
In my ViewController I have added A UISegmentedControl to preform different task for a different selection of the Segmented Control. Its a cards matching game.
And everything seems to work just fine, except that the Segmented Control is not reacting to the selection.., I created a switch to do something in case of "twoCardGame" and in case of "threeCardGame".
From what I understand it would be good to define those variables with enum, which I did in the top part of the controller, but it seems like i'm missing something in it..
Sorry if its not so directed, but my controller is pretty short and simple, would appreciate if you can tell me what am I doing wrong in term of the UISegmentedControl.
Here it is:
#import "CardGameViewController.h"
#import "PlayingCardsDeck.h"
#import "CardMatchingGame.h"
enum CardGame {
twoCardGame,
threeCardGame
};
#interface CardGameViewController ()
#property (weak, nonatomic) IBOutlet UILabel *notificationLabel;
#property (weak, nonatomic) IBOutlet UILabel *scoreCounter;
#property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
#property (strong, nonatomic) CardMatchingGame *game;
#property (weak, nonatomic) IBOutlet UISegmentedControl *numberOfCardsToPlayWith;
#end
#implementation CardGameViewController
//creating the getter method that creates a new card game.
- (CardMatchingGame *)game {
if (!_game) {
_game = [[CardMatchingGame alloc] initWithCardCount:self.cardButtons.count
usingDeck:[[PlayingCardsDeck alloc] init]];
_game.numberOfCardsToPlayWith = [self selectNumberOfCardsToPlayWith];
}
return _game;
}
//creating a setter for the IBOutletCollection cardButtons
-(void)setCardButtons:(NSArray *)cardButtons {
_cardButtons = cardButtons;
[self updateUI];
}
- (void)updateUI {
for (UIButton *cardButton in self.cardButtons) {
Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];
[cardButton setTitle:card.contents forState:UIControlStateSelected];
[cardButton setTitle:card.contents
forState:UIControlStateSelected|UIControlStateDisabled];
cardButton.selected = card.isFaceUp;
cardButton.enabled = !card.isUnplayable;
cardButton.alpha = card.isUnplayable ? 0.3 : 1.0;
}
self.scoreCounter.text = [NSString stringWithFormat:#"Score: %d", self.game.score];
}
//Here I created a method to flipCards when the card is selected, and give the user a random card from the deck each time he flips the card. After each flip i'm incrementing the flipCount setter by one.
- (IBAction)flipCard:(UIButton *)sender {
[self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];;
[self updateUI];
}
//sending an alert if the user clicked on new game button
- (IBAction)newGame:(UIButton *)sender {
UIAlertView* mes=[[UIAlertView alloc] initWithTitle:#"Think about it for a sec..?" message:#"This will start a new game" delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];
[mes show];
}
- (NSUInteger)selectNumberOfCardsToPlayWith {
switch (self.numberOfCardsToPlayWith.selectedSegmentIndex) {
case twoCardGame:
return 2;
case threeCardGame:
return 3;
default:
return 2;
}
[self updateUI];
}
//preforming an action according to the user choice for the alert yes/no to start a new game
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex != [alertView cancelButtonIndex]) {
self.game = nil;
for (UIButton *button in self.cardButtons) {
Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
card.isUnplayable = NO;
card.isFaceUp = NO;
button.alpha = 1;
}
self.notificationLabel.text = nil;
[self updateUI];
}
}
#end
Well, I don't see any addTarget: calls to segmented control. So you probably set them in Interface Builder. Check IB connections. If everything in IB seems ok -- try to addTarget: programmatically.
I think you'd be better off creating a selector and adding it to the segmented control target like so:
[segmentedControl addTarget:self
action:#selector(selectNumberOfCardsToPlayWith:)
forControlEvents:UIControlEventValueChanged];
- (NSUInteger)selectNumberOfCardsToPlayWith:(UISegmentedControl *)control {
switch (control.selectedSegmentIndex) {
case twoCardGame:
return 2;
case threeCardGame:
return 3;
default:
return 2;
}
[self updateUI];
}
This should work fine. Using similar code myself currently.
I have developed an application with in App Purchases. I have the following code... In the ViewController.m file I the butoon1Clicked Method I am callInAppPurchases. Actually when click on the button first time i want to perform In App Purchases. If the Transaction is Successful, from the next Click I want to Perform Some Action (For Example I gave NSLog Statement) Where Should I have to write the NSLog stmt(or any code) in the program to perform the Action when i click on the button after A successful Transaction. Please Exaplain me where i have to write. Or Explain me in any process. I thought i want to handle with BOOL Values but i am not able to know where i have to set the BOOL Value as YES / NO. Please Explain me... MyStoreObserver.m file do the In App Purchase Transactions.
ViewController.m
-(IBAction)button1Clicked:(id)sender
{
[self callInAppPurchase];
NSLoG(#"Perform Some Action");
}
#pragma mark-In-AppPurchase code from here
-(void)callInAppPurchase
{
if ([SKPaymentQueue canMakePayments])
{
// Display a store to the user.
}
}
AppDelegate.h
#import <UIKit/UIKit.h>
#import "MyStoreAbserver.h"
#interface iTeach_MathsAppDelegate : NSObject <UIApplicationDelegate>
{
BOOL isPurchased,isFailed;
}
#property (nonatomic, readwrite) BOOL isPurchased,isFailed;
#property (nonatomic, retain) IBOutlet UIWindow *window;
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
MyStoreAbserver *observer = [[MyStoreAbserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
if([[[NSUserDefaults standardUserDefaults] objectForKey:#"isPurchased"] isEqualToString:#"true"])
self.isPurchased = YES;
else
isPurchased = NO;
isFailed = NO;
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
I think you refer this link, and implement code... This link is useful for me...
When product purchase you call this function:
(void)productPurchased:(NSNotification *)notification
My URL map is as follows:
[map from:#"tt://webPage/(initWithPage:)" toSharedViewController:[WebPageController class]];
and in the WebPageController
- (id) initWithPage:(WebPage)page
{
if (self = [super init])
{
...
Then I called the url several times in my code
tt://webPage/1
tt://webPage/2
tt://webPage/1 (still called the initWithPage: everytime, not cached)
Why it is not cached as it is a SharedViewController?
I believe this is happening to you because TTNaviagtor is broken on iOS 5. see https://github.com/facebook/three20/pull/719/files. Have you tried running the same code on a iOS 4 with the same result?
My recommendation to you is to stop using TTNaviagtor. You can still use the three20 library by pushing and poping TTViewController in the native ios method.
Here's an example on replacing the TTNaviagtor in your app delegate:
#interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow* _window;
TTBaseNavigationController* _masterNavController;
WebPageController* _web1Controller;
WebPageController* _web2Controller;
}
#property(nonatomic, retain) UIWindow* window;
#property(nonatomic, retain) TTBaseNavigationController* masterNavController;
#property(nonatomic, retain) WebPageController* web1Controller;
#property(nonatomic, retain) WebPageController* web2Controller;
And
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#implementation AppDelegate
#synthesize window = _window;
#synthesize masterNavController = _masterNavController;
#synthesize web1Controller = _web1Controller;
#synthesize web2Controller = web2Controller;
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window = [[UIWindow alloc] initWithFrame:TTScreenBounds()];
TTViewController* controller = [[[MasterViewController alloc] init] autorelease];
_masterNavController = [[TTBaseNavigationController alloc] initWithRootViewController:controller];
[_window addSubview:_masterNavController.view];
}
[_window makeKeyAndVisible];
return YES;
}
then you can push and pop any TTViewController (or your own subclasses of TTViewController) into the _masterNavController. Personally, i think TTNavigator is a bad design pattern, and apple designed their navigation system in different mindset.
why not step into the code and check what happen?
I believe the objects are created in TTURLMap's objectForURL:query:pattern: you can set a break point and see why a new one is created instead re-use old one.
this the implementation of objectForURL:query:pattern: with my comment
- (id)objectForURL: (NSString*)URL
query: (NSDictionary*)query
pattern: (TTURLNavigatorPattern**)outPattern {
id object = nil;
if (_objectMappings) {
// _objectMappings is a NSMutableDictionary and use to cache shared object
object = [_objectMappings objectForKey:URL];
// if object not found than check does _objectMappings contains it with right key
if (object && !outPattern) {
return object;
}
}
NSURL* theURL = [NSURL URLWithString:URL];
TTURLNavigatorPattern* pattern = [self matchObjectPattern:theURL];
if (pattern) {
if (!object) {
// object is not found in the mapping dictionary so create new one, this should only happen once for shared object
object = [pattern createObjectFromURL:theURL query:query];
}
// make sure navigationMode is TTNavigationModeShare
if (pattern.navigationMode == TTNavigationModeShare && object) {
// cache shared object in the mapping dictionary so next time it will re-use the cached one
[self setObject:object forURL:URL];
// if setObject:forURL: is not working than the shared object will not be cached
}
if (outPattern) {
*outPattern = pattern;
}
return object;
} else {
return nil;
}
}
I have a custom UIWebView written like this :
.h
#interface MiniWebViewController : UIViewController {
NSString* destinationURL;
UIWebView* webView;
UIActivityIndicatorView* activityIndicatorView;
}
#property (nonatomic, retain) NSString* destinationURL;
#property (nonatomic, retain) IBOutlet UIWebView* webView;
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView* activityIndicatorView;
- (void) run;
#end
.m
#synthesize destinationURL;
#synthesize webView;
#synthesize activityIndicatorView;
- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithNibName:#"MiniWebView" bundle:nil]) {
self.destinationURL = #"";
self.view.frame = frame;
self.activityIndicatorView.center = self.webView.center;
}
return self;
}
- (void) run {
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.destinationURL]]];
}
It is called an initied from another ViewController :
- (void) aFunction {
MiniWebViewController* oneViewController = [[MiniWebViewController alloc] initWithFrame:CGRectMake(/*Some Rect*/];
oneViewController.webView.tag = i;
oneViewController.destinationURL = /*SomeURL*/;
oneViewController.webView.delegate = self;
[self.view addSubview:oneViewController.view]; /* the Web view is inside this one */
[oneViewController run];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
int webViewID = webView.tag;
MiniWebViewController* webViewController = [self.webViews objectAtIndex:webViewID];
[webViewController.activityIndicatorView stopAnimating];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
int webViewID = webView.tag;
MiniWebViewController* webViewController = [self.webViews objectAtIndex:webViewID];
[webViewController.activityIndicatorView startAnimating];
}
Into IB hidesWhenStopped is also checked. Everything is linked. The style of the indicator is set to "Large White" into IB.
When running, the indicator is not large, but small.
It is successfully started and stopped (delegate calls are triggered), but it doesn't hide when stopped.
What's the problem ? I don't see...
After a careful look in your code, you are modifying the UIActivityView in your init method. Change those so that they are in your viewDidLoad. At init, you view is not yet loaded, therefore, there is not an instance of those objects yet created in your controller.
These are the statement that need to be moved:
self.activityIndicatorView.hidesWhenStopped = YES;
self.view.frame = frame;
self.activityIndicatorView.center = self.webView.center;
This goes back to a fundamental of Objective-C: Sending a message to a nil object...returns nil. This is an annoying feature at times because there is no compile time warning, nor is there any runtime exception--a feature of the language.
Stupid I am, and XCode/cocoa really doesn't help.
I had loaded a wrong XIB name that DOES NOT exist.
So I ask to load something that does not exist, and the app stil works, even showing and using objects that does not exist. Untill one call does not work as expected. No crash...
It's nonsense.
Is there a way to manually set low-level still-camera settings like shutter speed, aperture, or ISO in iOS4 on the iPhone 4? I don't think it exists in the official SDK but perhaps someone has found some private APIs to allow this?
I find my iPhone 4 camera to be unusable because even in fairly decent lighting, it always insists on shooting at the slowest 1/15th a second shutter speed causing motion blur if the subject is moving at all.
Thanks!
Not directly. Please file a bug report.
Yes, there may be private APIs available, but that's of limited use.
Try this, I could be useful for you:
#interface MyViewController ()
#property (nonatomic, retain) IBOutlet UIImageView *imageView;
#property (nonatomic, retain) IBOutlet UIToolbar *myToolbar;
#property (nonatomic, retain) OverlayViewController *overlayViewController;
#property (nonatomic, retain) NSMutableArray *capturedImages;
// toolbar buttons
- (IBAction)photoLibraryAction:(id)sender;
- (IBAction)cameraAction:(id)sender;
#end
#implementation MyViewController
- (void)viewDidLoad
{
self.overlayViewController =
[[[OverlayViewController alloc] initWithNibName:#"OverlayViewController" bundle:nil] autorelease];
// as a delegate we will be notified when pictures are taken and when to dismiss the image picker
self.overlayViewController.delegate = self;
self.capturedImages = [NSMutableArray array];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
// camera is not on this device, don't show the camera button
NSMutableArray *toolbarItems = [NSMutableArray arrayWithCapacity:self.myToolbar.items.count];
[toolbarItems addObjectsFromArray:self.myToolbar.items];
[toolbarItems removeObjectAtIndex:2];
[self.myToolbar setItems:toolbarItems animated:NO];
}
}
- (void)viewDidUnload
{
self.imageView = nil;
self.myToolbar = nil;
self.overlayViewController = nil;
self.capturedImages = nil;
}
- (void)dealloc
{
[_imageView release];
[_myToolbar release];
[_overlayViewController release];
[_capturedImages release];
[super dealloc];
}
- (void)showImagePicker:(UIImagePickerControllerSourceType)sourceType
{
if (self.imageView.isAnimating)
[self.imageView stopAnimating];
if (self.capturedImages.count > 0)
[self.capturedImages removeAllObjects];
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
[self.overlayViewController setupImagePicker:sourceType];
[self presentModalViewController:self.overlayViewController.imagePickerController animated:YES];
}
}
- (IBAction)photoLibraryAction:(id)sender
{
[self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (IBAction)cameraAction:(id)sender
{
[self showImagePicker:UIImagePickerControllerSourceTypeCamera];
}
// as a delegate we are being told a picture was taken
- (void)didTakePicture:(UIImage *)picture
{
[self.capturedImages addObject:picture];
}
// as a delegate we are told to finished with the camera
- (void)didFinishWithCamera
{
[self dismissModalViewControllerAnimated:YES];
if ([self.capturedImages count] > 0)
{
if ([self.capturedImages count] == 1)
{
// we took a single shot
[self.imageView setImage:[self.capturedImages objectAtIndex:0]];
}
else
{
// we took multiple shots, use the list of images for animation
self.imageView.animationImages = self.capturedImages;
if (self.capturedImages.count > 0)
// we are done with the image list until next time
[self.capturedImages removeAllObjects];
self.imageView.animationDuration = 5.0; // show each captured photo for 5 seconds
self.imageView.animationRepeatCount = 0; // animate forever (show all photos)
[self.imageView startAnimating];
}
}
}
#end