I have a program that when I tap the view a UITextField will appear. I also have an Undo-Button. I wanted to make a delete function when I double tap the UITextfield it can be deleted. Please Help Me.
Here is my code:
ViewController.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface ViewController : UIViewController<UITextFieldDelegate, UIGestureRecognizerDelegate>
{
NSMutableArray *textfieldform;
UITextField *textField1;
float angle;
CGFloat beginX;
CGFloat beginY;
IBOutlet UIView *blahBlah;
CGPoint prevPanPoint;
float prevPinchScale;
float prevRotation;
}
#property (nonatomic, retain) NSMutableArray *textfieldform;
-(IBAction) undo;
- (IBAction)handleTap2:(UITapGestureRecognizer *)recognizer;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize text1, textfieldform;
- (void)viewDidLoad
{
[super viewDidLoad];
//textfieldform = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
textfieldform = [NSMutableArray arrayWithCapacity:0];
angle = 180;
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(scaleImage:)];
[blahBlah addGestureRecognizer:pinchGesture];
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:#selector(rotateImage:)];
[blahBlah addGestureRecognizer:rotationGesture];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panGestureAction:)];
[pan setMaximumNumberOfTouches:1];
[pan setMinimumNumberOfTouches:1];
[blahBlah addGestureRecognizer:rotationGesture];
UITapGestureRecognizer *twoFingersTwoTaps =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(twoFingersTwoTaps)] ];
[twoFingersTwoTaps setNumberOfTapsRequired:2];
[twoFingersTwoTaps setNumberOfTouchesRequired:2];
[blahBlah addGestureRecognizer:twoFingersTwoTaps];
}
- (void)twoFingersTwoTaps {
NSLog(#"Action: Delete text, two taps");
}
-(void)panGestureAction:(UIPanGestureRecognizer *)pan {
if (pan.state == UIGestureRecognizerStateBegan){
prevPanPoint = [pan locationInView:blahBlah];
}
CGPoint curr = [pan locationInView:blahBlah];
float diffx = curr.x - prevPanPoint.x;
float diffy = curr.y - prevPanPoint.y;
CGPoint centre = textField1.center;
centre.x += diffx;
centre.y += diffy;
textField1.center = centre;
prevPanPoint = curr;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if([touch.view isKindOfClass:[UIView class]]) {
return YES;
}
return NO;
}
- (void)scaleImage:(UIPinchGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateBegan)
prevPinchScale = 1.0;
float thisScale = 1 + (recognizer.scale-prevPinchScale);
prevPinchScale = recognizer.scale;
textField1.transform = CGAffineTransformScale(textField1.transform, thisScale, thisScale);
}
- (void)rotateImage:(UIRotationGestureRecognizer *)recognizer
{
if([recognizer state] == UIGestureRecognizerStateEnded) {
prevRotation = 0.0;
}
float thisRotate = recognizer.rotation - prevRotation;
prevRotation = recognizer.rotation;
textField1.transform = CGAffineTransformRotate(textField1.transform, thisRotate);
}
-(IBAction)undo{
UITextField *textFieldToRemove = [textfieldform lastObject];
if (textFieldToRemove) {
[textfieldform removeObject:textFieldToRemove];
[textFieldToRemove removeFromSuperview];
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
NSLog(#"textFieldShouldBeginEditing");
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
NSLog(#"textFieldDidBeginEditing");
[textField1 setBackgroundColor:[UIColor colorWithRed:(248/255.0) green:(248/255.0) blue:(255/255.0) alpha:1.0]];
textField1.borderStyle = UITextBorderStyleRoundedRect;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(#"textFieldShouldEndEditing");
textField.backgroundColor = [UIColor clearColor];
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(#"textFieldDidEndEditing");
[textField1 setBackgroundColor:[UIColor clearColor]];
textField1.borderStyle = UITextBorderStyleNone;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(#"textField:shouldChangeCharactersInRange:replacementString:");
if ([string isEqualToString:#"#"]) {
return NO;
}
else {
return YES;
}
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
NSLog(#"textFieldShouldClear:");
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(#"textFieldShouldReturn:");
if (textField.tag == textfieldform.count) {
textField1 = (UITextField *)[self.view viewWithTag:textfieldform.count];
[textField1 becomeFirstResponder];
}
else {
[textField resignFirstResponder];
}
return YES;
}
- (IBAction)handleTap2:(UITapGestureRecognizer *)recognizer{
if (recognizer.state == UIGestureRecognizerStateEnded){
CGPoint point = [recognizer locationInView:[self view]];
textField1 = [[UITextField alloc] init];
textField1.borderStyle = UITextBorderStyleLine;
textField1.font = [UIFont systemFontOfSize:15];
CGRect frame ;
frame.origin.x = point.x;
frame.origin.y = point.y;
frame.size.width=300;
frame.size.height=40;
textField1.frame=frame;
textField1.autocorrectionType = UITextAutocorrectionTypeNo;
textField1.keyboardType = UIKeyboardTypeDefault;
textField1.returnKeyType = UIReturnKeyDefault;
textField1.clearButtonMode = UITextFieldViewModeWhileEditing;
textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField1.delegate = self;
textField1.tag = textfieldform.count;
textField1.font = [UIFont fontWithName:#"Arial" size:30];
[textfieldform addObject:textField1];
[blahBlah addSubview:textField1];
[textField1 addTarget:self action:#selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
}
}
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event{
// get the touch
UITouch *touch = [[event touchesForView:textField1] anyObject];
// get delta
CGPoint previousLocation = [touch previousLocationInView:textField1];
CGPoint location = [touch locationInView:textField1];
CGFloat delta_x = location.x - previousLocation.x;
CGFloat delta_y = location.y - previousLocation.y;
// move button
textField1.center = CGPointMake(textField1.center.x + delta_x,textField1.center.y + delta_y);
}
- (void)moveImage:(UIPanGestureRecognizer *)recognizer
{
CGPoint newCenter = [recognizer translationInView:self.view];
if([recognizer state] == UIGestureRecognizerStateBegan) {
beginX = textField1.center.x;
beginY = textField1.center.y;
}
newCenter = CGPointMake(beginX + newCenter.x, beginY + newCenter.y);
[textField1 setCenter:newCenter];
}
- (void)viewDidUnload{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
UITextField *textFieldToRemove = [textfieldform objectAtIndex:0];
if (textFieldToRemove) {
NSLog(#"baaaaaaam! remove %i", textfieldform.count);
[textfieldform removeObject:textFieldToRemove];
[textFieldToRemove removeFromSuperview];
}
I kinda Figured it out. :)
Related
I am trying to make a vehicle (in this case a train) move based on player input. If I move the train via an SKAction, the wheels do not rotate. I could use the applyForce method on its physics body, but it I need more control. I need to make it move a certain distance over a certain amount of time. How can this be accomplished?
-(void)didMoveToView:(SKView *)view {
SKTexture *trainBodyTexture = [SKTexture textureWithImageNamed:#"levelselect_trainbody"];
SKSpriteNode *trainBody = [[SKSpriteNode alloc] initWithTexture:trainBodyTexture];
trainBody.zPosition = 0;
trainBody.position = CGPointMake(300, 500);
trainBody.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:trainBody.size];
[self addChild:trainBody];
SKTexture *trainWheelTexture = [SKTexture textureWithImageNamed:#"levelselect_trainwheel"];
SKSpriteNode *trainWheel1 = [[SKSpriteNode alloc] initWithTexture:trainWheelTexture];
trainWheel1.zPosition = 1;
trainWheel1.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:trainWheel1.size.width/2];
trainWheel1.physicsBody.allowsRotation = YES;
trainWheel1.position = CGPointMake(220, 400);
[self addChild:trainWheel1];
SKSpriteNode *trainWheel2 = [[SKSpriteNode alloc] initWithTexture:trainWheelTexture];
trainWheel2.zPosition = 1;
trainWheel2.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:trainWheel2.size.width/2];
trainWheel2.physicsBody.allowsRotation = YES;
trainWheel2.position = CGPointMake(380, 400);
[self addChild:trainWheel2];
SKShapeNode *dot = [SKShapeNode shapeNodeWithCircleOfRadius:10];
dot.zPosition = 2;
dot.fillColor = [NSColor redColor];
dot.position = CGPointMake(0, -20);
[trainWheel1 addChild:dot];
SKPhysicsJointPin *pin = [SKPhysicsJointPin jointWithBodyA:trainBody.physicsBody bodyB:trainWheel1.physicsBody anchor:trainWheel1.position];
SKPhysicsJointPin *pin2 = [SKPhysicsJointPin jointWithBodyA:trainBody.physicsBody bodyB:trainWheel2.physicsBody anchor:trainWheel2.position];
[self.scene.physicsWorld addJoint:pin];
[self.scene.physicsWorld addJoint:pin2];
//[trainWheel1 runAction:[SKAction moveByX:300 y:0 duration:3]];
[trainBody.physicsBody applyForce:CGVectorMake(3000, 0)];
}
UPDATE: Implemented With A Train Class (suggested by Jaffer Sheriff)
Train.h
#import <SpriteKit/SpriteKit.h>
#interface Train : SKSpriteNode
-(void) createPhysics;
-(void) moveLeft;
-(void) moveRight;
#end
Train.m
#import "Train.h"
#interface Train()
#property SKSpriteNode *trainBody, *trainWheelFront, *trainWheelRear;
#property SKPhysicsWorld *physicsWorld;
#end
#implementation Train
-(instancetype) init {
if (self = [super init]) {
[self initTrainBody];
[self initWheels];
}
return self;
}
-(void) initTrainBody {
SKTexture *trainBodyTexture = [SKTexture textureWithImageNamed:#"levelselect_trainbody"];
_trainBody = [[SKSpriteNode alloc] initWithTexture:trainBodyTexture];
_trainBody.zPosition = 0;
_trainBody.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_trainBody.size];
[self addChild:_trainBody];
}
-(void) initWheels {
SKTexture *_trainWheelTexture = [SKTexture textureWithImageNamed:#"levelselect_trainwheel"];
_trainWheelFront = [[SKSpriteNode alloc] initWithTexture:_trainWheelTexture];
_trainWheelFront.zPosition = 1;
_trainWheelFront.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:_trainWheelFront.size.width/2];
_trainWheelFront.physicsBody.allowsRotation = YES;
_trainWheelFront.position = CGPointMake(-80, -82);
[self addChild:_trainWheelFront];
_trainWheelRear = [[SKSpriteNode alloc] initWithTexture:_trainWheelTexture];
_trainWheelRear.zPosition = 1;
_trainWheelRear.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:_trainWheelRear.size.width/2];
_trainWheelRear.physicsBody.allowsRotation = YES;
_trainWheelRear.position = CGPointMake(80, -82);
[self addChild:_trainWheelRear];
//dot used to see if wheels are rotating, no other point
SKShapeNode *dot = [SKShapeNode shapeNodeWithCircleOfRadius:10];
dot.zPosition = 2;
dot.fillColor = [NSColor redColor];
dot.position = CGPointMake(0, -20);
[_trainWheelFront addChild:dot];
}
//this method is called after the train node is added to the scene in GameScene otherwise will get error adding joints before node is in scene
-(void) createPhysics {
SKPhysicsJointPin *pin = [SKPhysicsJointPin jointWithBodyA:_trainBody.physicsBody bodyB:_trainWheelFront.physicsBody anchor:_trainWheelFront.position];
SKPhysicsJointPin *pin2 = [SKPhysicsJointPin jointWithBodyA:_trainBody.physicsBody bodyB:_trainWheelRear.physicsBody anchor:_trainWheelRear.position];
[self.scene.physicsWorld addJoint:pin];
[self.scene.physicsWorld addJoint:pin2];
}
-(void) moveLeft {
SKAction *rotateLeft = [SKAction rotateByAngle:6*M_PI duration:0.2];
[_trainWheelFront runAction:rotateLeft];
[_trainWheelRear runAction:rotateLeft];
}
-(void) moveRight {
SKAction *rotateRight = [SKAction rotateByAngle:-6*M_PI duration:0.2];
[_trainWheelFront runAction:rotateRight];
[_trainWheelRear runAction:rotateRight];
}
#end
GameScene.m
#import "GameScene.h"
#import "Train.h"
#interface GameScene()
#property Train *train;
#end
#implementation GameScene
-(void)didMoveToView:(SKView *)view {
[self initTrain];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyPressed:) name:#"KeyPressedNotificationKey" object:nil]; //using notifications and custom view class to handle key presses
}
-(void) initTrain {
_train = [[Train alloc] init];
_train.position = CGPointMake(500, 300);
[self addChild:_train];
[_train createPhysics];
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
-(void) keyPressed:(NSNotification*)notification {
NSNumber *keyCodeObject = notification.userInfo[#"keyCode"];
NSInteger keyCode = keyCodeObject.integerValue;
NSLog(#"keycode = %lu", keyCode);
switch (keyCode) {
case 123:
[self leftArrowPressed];
break;
case 124:
[self rightArrowPressed];
break;
}
}
-(void) leftArrowPressed {
SKAction *moveLeft = [SKAction moveByX:-200 y:0 duration:0.2];
[_train runAction:moveLeft];
[_train moveLeft];
}
-(void) rightArrowPressed {
SKAction *moveRight = [SKAction moveByX:200 y:0 duration:0.2];
[_train runAction:moveRight];
[_train moveRight];
}
#end
Note: This solution causes the entire train to flip and freak out when the left/right keys are pressed. It seems like my pin joints are incorrect, but they seem correct to me :/
Default Initializer of SkSpriteNode is - (instancetype)initWithTexture:(SKTexture *)texture color:(SKColor *)color size:(CGSize)size; Try this,
#interface Train : SKSpriteNode
- (instancetype)initTrainWithColor:(UIColor *) color andSize:(CGSize) size;
-(void) animateWheelsWithTime:(float) time;
#end
#interface Train ()
{
SKSpriteNode *wheel1;
SKSpriteNode *wheel2;
NSMutableArray *wheelsArray;
}
#end
#implementation Train
- (instancetype)initTrainWithColor:(UIColor *) color andSize:(CGSize) size
{
self = [super initWithTexture:nil color:color size:size];
if (self)
{
[self addWheels];
}
return self;
}
-(void)addWheels
{
wheelsArray = [[NSMutableArray alloc]init];
wheel1 = [SKSpriteNode spriteNodeWithImageNamed:#"wheel"];
[wheel1 setPosition:CGPointMake(-(self.frame.size.width/2.0f-wheel1.frame.size.width/2.0f), - (self.frame.size.height/2.0f - wheel1.frame.size.height/2.0f))];
[self addChild:wheel1];
wheel2 = [SKSpriteNode spriteNodeWithImageNamed:#"wheel"];
[wheel2 setPosition:CGPointMake((self.frame.size.width/2.0f-wheel2.frame.size.width/2.0f), - (self.frame.size.height/2.0f - wheel2.frame.size.height/2.0f))];
[self addChild:wheel2];
[wheelsArray addObject:wheel1];
[wheelsArray addObject:wheel2];
}
-(void) animateWheelsWithTime:(float) time
{
for (SKSpriteNode *wheel in wheelsArray)
{
SKAction *act = [SKAction rotateByAngle:3*M_PI duration:time];
[wheel runAction:act];
}
}
#end
In GameScene.m add train like this,
-(void) addTrain
{
Train *train1 = [[Train alloc]initTrainWithColor:[UIColor yellowColor] andSize:CGSizeMake(150, 100)];
[train1 setPosition:CGPointMake(self.size.width/2.0f, self.size.height/2.0f)];
[self addChild:train1];
SKAction *act = [SKAction moveTo:CGPointMake(self.size.width/2.0f, self.size.height - 50) duration:2];
[train1 runAction:act];
[train1 animateWheelsWithTime:2];
}
I tried and it works.
I have a game with a menu scene, a play scene, and a game over scene. When I am on one of them is there a way to not run the others in the background. For example on my play scene when you make contact with something it switches to the game over scene. When I'm on the menu scene the play scene runs and when it makes contact it switches to the game over scene.
So My Question is: Can I make it so that the scene won't run in the background? Or a way to delay it until I press the play button on the menu?
Here is the code for the first scene:
#import "WEMenuScene.h"
#import "WEMyScene.h"
#implementation WEMenuScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.scaleMode = SKSceneScaleModeAspectFill;
SKSpriteNode* background = [SKSpriteNode spriteNodeWithImageNamed:#"landscape"];
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
background.zPosition = 1000;
[self addChild:background];
[self addChild:[self playButton]];
}
return self;
}
-(SKSpriteNode *) playButton {
SKSpriteNode* play = [SKSpriteNode spriteNodeWithImageNamed:#"Play"];
play.position = CGPointMake(CGRectGetMidX(self.frame), 300);
play.zPosition = 1200;
play.name = #"playButton";
return play;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode* node = [self nodeAtPoint:location];
if ([node.name isEqualToString:#"playButton"]) {
SKScene* playScene = [[WEMyScene alloc] initWithSize:self.size];
SKTransition* transitionPlay = [SKTransition doorsOpenVerticalWithDuration:0.5];
[self.view presentScene:playScene transition:transitionPlay];
}
}
#end
Here is the code for the second scene:
#import "WEMyScene.h"
#import "WECapturedScene.h"
#implementation WEMyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.scaleMode = SKSceneScaleModeAspectFill;
[self performSelector:#selector(logs) withObject:nil afterDelay:3.0];
[self performSelector:#selector(moveBackground) withObject:nil afterDelay:0.0];
[self addChild:[self createCharacter]];
[self setUpActions];
}
return self;
}
-(SKSpriteNode *) createCharacter {
SKSpriteNode* holly = [SKSpriteNode spriteNodeWithImageNamed:#"holly1"];
holly.position = CGPointMake(CGRectGetMidX(self.frame), 185);
holly.name = #"holly";
holly.zPosition = 40;
return holly;
}
-(void) logs {
CGPoint startPoint = CGPointMake(480, 175);
SKSpriteNode* logs = [SKSpriteNode spriteNodeWithImageNamed:#"log"];
logs.position = CGPointMake(startPoint.x, startPoint.y);
logs.name = #"logs";
logs.zPosition = 40;
[self addChild:logs];
float spawnLog = arc4random_uniform(3)+ 1.4;
[self performSelector:#selector(logs) withObject:nil afterDelay:spawnLog];
}
-(void) setUpActions {
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:#"Holly"];
SKTexture *movetex1 = [atlas textureNamed:#"holly1"];
SKTexture *movetex2 = [atlas textureNamed:#"holly2"];
SKTexture *movetex3 = [atlas textureNamed:#"holly3"];
SKTexture *movetex4 = [atlas textureNamed:#"holly4"];
SKTexture *movetex5 = [atlas textureNamed:#"holly5"];
SKTexture *movetex6 = [atlas textureNamed:#"holly6"];
SKTexture *movetex7 = [atlas textureNamed:#"holly7"];
NSArray *atlasTexture = #[movetex1, movetex2, movetex3, movetex4, movetex5, movetex6, movetex7];
SKAction* atlasAnimation =[SKAction repeatActionForever:[SKAction animateWithTextures:atlasTexture timePerFrame:0.08]];
hollyMovement = [SKAction sequence:#[atlasAnimation]];
SKSpriteNode* holly = (SKSpriteNode*)[self childNodeWithName:#"holly"];
holly.zPosition = 40;
[holly runAction:hollyMovement];
SKAction* moveUp = [SKAction moveByX:0 y:90 duration:0.50];
SKAction* wait = [SKAction moveByX:0 y:0 duration:0.4];
SKAction* moveDown = [SKAction moveByX:0 y:-90 duration:0.4];
SKAction* done = [SKAction performSelector:#selector(jumpDone) onTarget:self];
hollyUp = [SKAction sequence:#[moveUp, wait, moveDown, done]];
}
-(void) jumpDone {
isJumping = NO;
}
-(void) moveBackground {
CGPoint startPoint = CGPointMake(480, 230);
SKSpriteNode* landscape = [SKSpriteNode spriteNodeWithImageNamed:#"landscape"];
landscape.position = CGPointMake(startPoint.x, startPoint.y);
landscape.name = #"landscape";
landscape.zPosition = 1;
[self addChild:landscape];
float spawnbackground = 0.7;
[self performSelector:#selector(moveBackground) withObject:nil afterDelay:spawnbackground];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
if (isJumping == NO) {
isJumping = YES;
SKSpriteNode* holly = (SKSpriteNode*)[self childNodeWithName:#"holly"];
[holly runAction:hollyUp];
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
SKNode* holly = [self childNodeWithName:#"holly"];
[self enumerateChildNodesWithName:#"landscape" usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.x < 0 || node.position.y < 0) {
[node removeFromParent];
}else {
node.position = CGPointMake(node.position.x - 10, node.position.y);
}
}];
[self enumerateChildNodesWithName:#"logs" usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.x < 0 || node.position.y < 0) {
[node removeFromParent];
}else {
node.position = CGPointMake(node.position.x - 10, node.position.y);
}
if ([holly intersectsNode:node]) {
SKScene *capturedScene = [[WECapturedScene alloc] initWithSize:self.size];
SKTransition* transition = [SKTransition doorsOpenVerticalWithDuration:0.5];
[self.view presentScene:capturedScene transition:transition];
}
}];
[self enumerateChildNodesWithName:#"dogCatcher" usingBlock:^(SKNode *node, BOOL *stop) {
node.position = CGPointMake(node.position.x + 10, node.position.y);
}];
}
Here is the view controller:
#import "WEViewController.h"
#import "WEMyScene.h"
#import "WEMenuScene.h"
#implementation WEViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
// Create and configure the scene.
SKScene * scene = [WEMenuScene sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:scene];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskAllButUpsideDown;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
#end
I'm having problems with my HighScore. I can see my HighScore in the HighScore label when i'm finished running the app, but when i quit my application and relaunch it, the HighScore disappears... Can somebody tell me what's wrong?
Here is my .h file:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
int Y;
BOOL Start;
BOOL applications;
int RandomPosition;
int Scorenumber;
int HighScore;
#interface ViewController : UIViewController
{
SystemSoundID SoundId;
IBOutlet UILabel *Intro1;
IBOutlet UILabel *Intro2;
IBOutlet UILabel *Intro3;
IBOutlet UIImageView *Heli;
NSTimer *timer;
IBOutlet UIImageView *Obstacle;
IBOutlet UIImageView *Obstacle2;
IBOutlet UIImageView *Obstacle3;
IBOutlet UIImageView *Obstacle4;
IBOutlet UIImageView *Obstacle5;
IBOutlet UIImageView *Obstacle6;
IBOutlet UIImageView *Obstacle7;
IBOutlet UIImageView *Obstacle8;
IBOutlet UIImageView *Obstacle9;
IBOutlet UIImageView *Bottom1;
IBOutlet UIImageView *Bottom2;
IBOutlet UIImageView *Top2;
IBOutlet UIImageView *Top1;
IBOutlet UIImageView *corona;
IBOutlet UILabel *Score;
NSTimer *Scorer;
}
#end
And here is my .m file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)Collision{
if (CGRectIntersectsRect(Heli.frame, Obstacle.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Obstacle2.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Bottom1.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Top1.frame)) {
[self EndGame];
}
}
-(void)EndGame{
if (Scorenumber > HighScore) {
HighScore = Scorenumber;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber
numberWithInt:HighScore] forKey:#"HighScoreSaved"];
}
Heli.hidden = YES;
[timer invalidate];
[Scorer invalidate];
[self performSelector:#selector(NewGame) withObject: nil afterDelay:2];
}
-(void)NewGame{
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(88, 286);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
}
-(void)HeliMove{
[self Collision];
Heli.center = CGPointMake(Heli.center.x, Heli.center.y + Y);
Obstacle.center = CGPointMake(Obstacle.center.x -5, Obstacle.center.y);
Obstacle2.center = CGPointMake(Obstacle2.center.x -5, Obstacle2.center.y);
Bottom1.center = CGPointMake(Bottom1.center.x -5, Bottom1.center.y -0);
Top1.center = CGPointMake(Top1.center.x -5, Top1.center.y -0);
corona.center = CGPointMake(corona.center.x -5, corona.center.y );
if (Obstacle.center.x < -70) {
RandomPosition = arc4random() %185;
RandomPosition = RandomPosition + 170;
Obstacle.center = CGPointMake(300, RandomPosition);
}
if (Obstacle2.center.x < 0) {
RandomPosition = arc4random() %165;
RandomPosition = RandomPosition + 600;
Obstacle.center = CGPointMake(300, RandomPosition);
}
if (Top1.center.x <-100) {
RandomPosition = arc4random() %80;
Top1.center = CGPointMake(400, 17);
RandomPosition = RandomPosition + 495;
Bottom1.center = CGPointMake(400, 540);
}
if (corona.center.x < -3000) {
RandomPosition = arc4random() %165;
RandomPosition = RandomPosition + 110;
corona.center = CGPointMake(6000, 162);
}
}
-(void)Scoring{
Scorenumber = Scorenumber + 1;
Score.text = [NSString stringWithFormat:#"Score: %i", Scorenumber];
if (CGRectIntersectsRect(Heli.frame, corona.frame)) {
Scorenumber = Scorenumber + 20;
corona.hidden = YES;
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if (Start == YES) {
AudioServicesPlaySystemSound(SoundId);
Intro1.hidden = YES;
Intro2.hidden = YES;
Intro3.hidden = YES;
timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self
selector:#selector(HeliMove) userInfo:nil repeats:YES];
Scorer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:#selector(Scoring) userInfo:nil repeats:YES];
Start = NO;
Bottom1.hidden = NO;
Top1.hidden = NO;
Obstacle.hidden = NO;
Obstacle2.hidden = NO;
Obstacle3.hidden = NO;
Obstacle4.hidden = NO;
Obstacle5.hidden = NO;
Obstacle6.hidden = NO;
Obstacle7.hidden = NO;
Obstacle8.hidden = NO;
Obstacle9.hidden = NO;
corona.hidden = NO;
RandomPosition = arc4random() %150;
RandomPosition = RandomPosition + 397;
Obstacle.center = CGPointMake(570, RandomPosition);
RandomPosition = arc4random() %75;
RandomPosition = RandomPosition + 259;
Obstacle2.center = CGPointMake(855, RandomPosition);
RandomPosition = arc4random() %55;
corona.center = CGPointMake(1040, 162);
}
Y = -7;
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
Y = 7;
Heli.image = [UIImage imageNamed:#"buss til app ned.png"];
}
- (void)viewDidLoad
{
// Get your highscore from the prefs.
HighScore = [[[NSUserDefaults standardUserDefaults] objectForKey:#"HighScore"]
intValue ];
Start = YES;
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
Obstacle3.hidden = YES;
Obstacle4.hidden = YES;
Obstacle5.hidden = YES;
Obstacle6.hidden = YES;
Obstacle7.hidden = YES;
Obstacle8.hidden = YES;
Obstacle9.hidden = YES;
corona.hidden = YES;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
It would really be helpful if someone could answer this :)
I'm kinda tired of this after sitting with it for HOURS!
Your putting your high score into NSUserDefaults with the key:
forKey:#"HighScoreSaved"];
But you are trying to pull it out with:
objectForKey:#"HighScore"]
Your key needs to be the same in both places. Or in other words, you have to write to, and read from NSUserDefaults with the same key.
Nested uiscrolls in a larger uiscroll need to, when zoomed, reset zoom level when they are off screen. I am trying to reset all of them when the scrolling ends but no luck. Any ideas?
myScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];
myScrollview.pagingEnabled = YES;
myScrollview.scrollEnabled =YES;
myScrollview.clipsToBounds = NO;
myScrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;
myScrollview.showsHorizontalScrollIndicator = YES;
myScrollview.backgroundColor = [UIColor blackColor];
myScrollview.delegate = self;
NSInteger viewcount=4;
NSArray *images = [NSArray arrayWithObjects:[UIImage imageNamed:#"01.png"],[UIImage imageNamed:#"02.png"],[UIImage imageNamed:#"03.png"],[UIImage imageNamed:#"04.png"],nil];
for (int i = 0; i <viewcount; i++)
{
CGFloat x = i * self.view.frame.size.width;
subView = [[UIScrollView alloc]initWithFrame:CGRectMake(x, 0, self.view.frame.size.width, self.view.frame.size.height)];
[subView setBackgroundColor:[UIColor blackColor]];
[subView setCanCancelContentTouches:NO];
subView.clipsToBounds = NO; // default is NO, we want to restrict drawing within our scrollview
subView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
aImageView = [[UIImageView alloc ] initWithImage:[images objectAtIndex:i]];
[self.aImageView setTag:viewcount];
[subView addSubview:aImageView];
[subView setContentSize:CGSizeMake(aImageView.frame.size.width, subView.frame.size.height)];
subView.minimumZoomScale = 1;
subView.maximumZoomScale = 3;
subView.delegate = self;
[subView setScrollEnabled:YES];
subView.contentSize = aImageView.frame.size;
[myScrollview addSubview:subView];
}
myScrollview.contentSize = CGSizeMake(self.view.frame.size.width*viewcount,self.view.frame.size.height);
[self.view addSubview:myScrollview];
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
NSLog (#"test");
UIView * view = nil;
view = [subView viewWithTag:0];
//return view;
return [scrollView.subviews objectAtIndex:0];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(#"Did scroll");
[self resetImageZoom];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
= NSLog(#"Did end decal");
[self resetImageZoom];
}
-(void)resetImageZoom {
NSLog(#"Resetting any image zoom");
for(UIView *view in [myScrollview subviews]) {
//if([view isKindOfClass:[UIScrollView class]]) {
//[(UIScrollView*)view setZoomScale:1.0 animated:NO];
//}
view.transform = CGAffineTransformIdentity;
}
}
That did it...
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(#"Did end dece");
for (UIView *view in scrollView.subviews) {
if([view isKindOfClass:[UIScrollView class]]) {
[(UIScrollView*)view setZoomScale:1.0 animated:NO];
}
}
}
I downloaded a dome about UIScorllView and UIPageControl. Why UIPageControl is not display?
Here is the code ,I am new in Iphone .Any help will be appreciated!
ScrollView.M I put the ResultViewController into ScrollView. I want scroll the resultViewController with PageController.
- (void)loadScrollViewWithPage:(int)page
{
if (page < 0)
return;
if (page >= pageNumber)
return;
ResultViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{
controller = [[ResultViewController alloc] initWithPageNumber:page locations:existLocations];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
if (controller.view.superview == nil)
{
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
existLocations = [FileManagerUtil readPlistFileForDictionary:#"Locations" fileName:#"CloudCheckLocations.plist"];
pageNumber = [existLocations count];
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < pageNumber; i++)
{
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[self.navigationItem setTitle:#"NetWork condition"];
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * pageNumber, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageContronl.numberOfPages = pageNumber;
pageContronl.currentPage = 0;
[pageContronl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
[pageContronl setBackgroundColor:[UIColor blackColor]];
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
[scrollView addSubview:pageContronl];
[self.view addSubview:scrollView];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
if (pageControlUsed)
{
return;
}
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageContronl.currentPage = page;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
pageControlUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender
{
int page = pageContronl.currentPage;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
pageControlUsed = YES;
}
ScrollView.h
#interface ScrollViewController : UIViewController<UIScrollViewDelegate>
{
NSMutableArray *viewControllers;
NSString *currectNetWork;
NSString *flag;
NSString *locationName;
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageContronl;
BOOL pageControlUsed;
int pageNumber;
NSMutableDictionary *existLocations;
}
#property (nonatomic,retain) NSString *currectNetWork;
#property (nonatomic,retain) NSString *flag;
#property (nonatomic,retain) NSString *locationName;
#property (nonatomic,retain) UIPageControl * pageContronl;
#property (nonatomic,retain) UIScrollView * scrollView;
#property (nonatomic,retain) NSMutableArray *viewControllers;
#property (nonatomic,retain) NSMutableDictionary *existLocations;
(IBAction)changePage:(id)sender;
ResultViewControl.M
This method will call by ScrollView.M
- (id)initWithPageNumber:(int)page locations :(NSMutableDictionary *) locations
{
titilArray = [[NSArray alloc] initWithObjects:#"Today", #"Past 7 Day",#"Past 30 Day",nil];
if (self = [super initWithNibName:#"ResultViewController" bundle:nil])
{
pageNumber = page;
existLocations = locations;
}
return self;
}
Check the background colour of pageControl and parent view. If both have same colour (default white) page control will not display.
In IOS6, you have new methods pageIndicatorTintColor and currentPageIndicatorTintColor.
Hope this will help.
Check your top and bottom constraints of container view/ tableView(if present). Both must not be attached with Top/Bottom Layout Guide. Attach them with container Margins.