I'm making a game and I want to have a button. How do I handle tapping it?
I use separate class for UI, it is SKSpriteNode that holds all buttons and interface elements, and I don't want Scene to handle those button presses for me in touches began method.
As I know we can check for node that is being touched in touches began, so to implement regular button with touch up inside I need to write code in touchesBegan and touchesEnded, this looks like a bit overkill.
Or should I use regular UIButton? But I know that you can't add those dynamically, only in didMoveToView method, and this looks bad.
I found this online a while ago, courtesy of a member who goes by the name of Graf, this works nicely for my problems.
#import <SpriteKit/SpriteKit.h>
#interface SKBButtonNode : SKSpriteNode
#property (nonatomic, readonly) SEL actionTouchUpInside;
#property (nonatomic, readonly) SEL actionTouchDown;
#property (nonatomic, readonly) SEL actionTouchUp;
#property (nonatomic, readonly, weak) id targetTouchUpInside;
#property (nonatomic, readonly, weak) id targetTouchDown;
#property (nonatomic, readonly, weak) id targetTouchUp;
#property (nonatomic) BOOL isEnabled;
#property (nonatomic) BOOL isSelected;
#property (nonatomic, readonly, strong) SKLabelNode *title;
#property (nonatomic, readwrite, strong) SKTexture *normalTexture;
#property (nonatomic, readwrite, strong) SKTexture *selectedTexture;
#property (nonatomic, readwrite, strong) SKTexture *disabledTexture;
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected;
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected disabled:(SKTexture *)disabled; // Designated Initializer
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected;
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected disabled:(NSString *)disabled;
/** Sets the target-action pair, that is called when the Button is tapped.
"target" won't be retained.
*/
- (void)setTouchUpInsideTarget:(id)target action:(SEL)action;
- (void)setTouchDownTarget:(id)target action:(SEL)action;
- (void)setTouchUpTarget:(id)target action:(SEL)action;
#end
And the implementation
//
//
// Courtesy of Graf on Stack Overflow
//
//
//
#import "SKBButtonNode.h"
#implementation SKBButtonNode
#pragma mark Texture Initializer
/**
* Override the super-classes designated initializer, to get a properly set SKButton in every case
*/
- (instancetype)initWithTexture:(SKTexture *)texture color:(UIColor *)color size:(CGSize)size {
return [self initWithTextureNormal:texture selected:nil disabled:nil];
}
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected {
return [self initWithTextureNormal:normal selected:selected disabled:nil];
}
/**
* This is the designated Initializer
*/
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected disabled:(SKTexture *)disabled {
self = [super initWithTexture:normal color:[UIColor whiteColor] size:normal.size];
if (self) {
[self setNormalTexture:normal];
[self setSelectedTexture:selected];
[self setDisabledTexture:disabled];
[self setIsEnabled:YES];
[self setIsSelected:NO];
_title = [SKLabelNode labelNodeWithFontNamed:#"Arial"];
[_title setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
[_title setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
[self addChild:_title];
[self setUserInteractionEnabled:YES];
}
return self;
}
#pragma mark Image Initializer
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected {
return [self initWithImageNamedNormal:normal selected:selected disabled:nil];
}
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected disabled:(NSString *)disabled {
SKTexture *textureNormal = nil;
if (normal) {
textureNormal = [SKTexture textureWithImageNamed:normal];
}
SKTexture *textureSelected = nil;
if (selected) {
textureSelected = [SKTexture textureWithImageNamed:selected];
}
SKTexture *textureDisabled = nil;
if (disabled) {
textureDisabled = [SKTexture textureWithImageNamed:disabled];
}
return [self initWithTextureNormal:textureNormal selected:textureSelected disabled:textureDisabled];
}
#pragma -
#pragma mark Setting Target-Action pairs
- (void)setTouchUpInsideTarget:(id)target action:(SEL)action {
_targetTouchUpInside = target;
_actionTouchUpInside = action;
}
- (void)setTouchDownTarget:(id)target action:(SEL)action {
_targetTouchDown = target;
_actionTouchDown = action;
}
- (void)setTouchUpTarget:(id)target action:(SEL)action {
_targetTouchUp = target;
_actionTouchUp = action;
}
#pragma -
#pragma mark Setter overrides
- (void)setIsEnabled:(BOOL)isEnabled {
_isEnabled = isEnabled;
if ([self disabledTexture]) {
if (!_isEnabled) {
[self setTexture:_disabledTexture];
} else {
[self setTexture:_normalTexture];
}
}
}
- (void)setIsSelected:(BOOL)isSelected {
_isSelected = isSelected;
if ([self selectedTexture] && [self isEnabled]) {
if (_isSelected) {
[self setTexture:_selectedTexture];
} else {
[self setTexture:_normalTexture];
}
}
}
#pragma -
#pragma mark Touch Handling
/**
* This method only occurs, if the touch was inside this node. Furthermore if
* the Button is enabled, the texture should change to "selectedTexture".
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self isEnabled]) {
if (_actionTouchDown){
[self.parent performSelectorOnMainThread:_actionTouchDown withObject:_targetTouchDown waitUntilDone:YES];
[self setIsSelected:YES];
}
}
}
/**
* If the Button is enabled: This method looks, where the touch was moved to.
* If the touch moves outside of the button, the isSelected property is restored
* to NO and the texture changes to "normalTexture".
*/
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self isEnabled]) {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self.parent];
if (CGRectContainsPoint(self.frame, touchPoint)) {
[self setIsSelected:YES];
} else {
[self setIsSelected:NO];
}
}
}
/**
* If the Button is enabled AND the touch ended in the buttons frame, the
* selector of the target is run.
*/
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self.parent];
if ([self isEnabled] && CGRectContainsPoint(self.frame, touchPoint)) {
if (_actionTouchUpInside){
[self.parent performSelectorOnMainThread:_actionTouchUpInside withObject:_targetTouchUpInside waitUntilDone:YES];
}
}
[self setIsSelected:NO];
if (_actionTouchUp){
[self.parent performSelectorOnMainThread:_actionTouchUp withObject:_targetTouchUp waitUntilDone:YES];
}
}
#end
I had created a class for using SKSpriteNode as a button quite a while ago. You can find it on GitHub here.
AGSpriteButton
It's implementation is based on UIButton, so if you are already familiar with iOS, you should find it easy to work with.
It includes a method to set up a label as well.
A button will typically be declared like so:
AGSpriteButton *button = [AGSpriteButton buttonWithColor:[UIColor redColor] andSize:CGSizeMake(300, 100)];
[button setLabelWithText:#"Button Text" andFont:nil withColor:nil];
button.position = CGPointMake(self.size.width / 2, self.size.height / 3);
[button addTarget:self selector:#selector(someSelector) withObject:nil forControlEvent:AGButtonControlEventTouchUpInside];
[self addChild:button];
And that's it. You're good to go.
EDIT: Since posting this answer, a few enhancements have been made to AGSpriteButton.
You can now assign blocks to be executed on touch events:
[button performBlock:^{
[self addSpaceshipAtPoint:[NSValue valueWithCGPoint:CGPointMake(100, 100)]];
} onEvent:AGButtonControlEventTouchUp];
Also, an SKAction object to be performed on an instance of SKNode (or any of it's subclasses) can be assigned:
[button addTarget:self
selector:#selector(addSpaceshipAtPoint:)
withObject:[NSValue valueWithCGPoint:CGPointMake(self.size.width / 2, self.size.height / 2)]
forControlEvent:AGButtonControlEventTouchUpInside];
AGSpriteButton can be used with Swift as well!
let button = AGSpriteButton(color: UIColor.greenColor(), andSize: CGSize(width: 200, height: 60))
button.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
button.addTarget(self, selector: "addSpaceship", withObject: nil, forControlEvent:AGButtonControlEvent.TouchUpInside)
button.setLabelWithText("Spaceship", andFont: nil, withColor: UIColor.blackColor())
addChild(button)
Related
I am currently learning drawing with UIView and CALayer. I quickly did a drawing app to experiment with the two classes. I noticed CALayer had worse performance than UIView. Here is the code:
myView.m
#interface myView()
#property (nonatomic, strong) UIImageView *background;
#ifdef USE_LAYER
#property (nonatomic, strong) drawingLayer *drawCanvas;
#else
#property (nonatomic, strong) drawingView *drawCanvas;
#endif
#end
#implementation myView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
self.background = [[UIImageView alloc] initWithFrame:frame];
[self addSubview:self.background];
#ifdef USE_LAYER
self.drawCanvas = [[drawingLayer alloc] init];
self.drawCanvas.frame = frame;
[self.layer addSublayer:self.drawCanvas];
#else
self.drawCanvas = [[drawingView alloc] initWithFrame:frame];
self.drawCanvas.backgroundColor = [UIColor clearColor];
[self addSubview:self.drawCanvas];
#endif
}
return self;
}
- (CGPoint)getPoint:(NSSet<UITouch *> *)touches
{
NSArray *touchesArray = [touches allObjects];
UITouch *touch = (UITouch *)[touchesArray objectAtIndex:0];
return [touch locationInView:self];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGPoint point = [self getPoint:touches];
self.drawCanvas.points = [[NSMutableArray alloc] init];
self.drawCanvas.startPoint = point;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGPoint point = [self getPoint:touches];
[self.drawCanvas.points addObject:[NSValue valueWithCGPoint:point]];
self.background.image = [self imageFromLayer:self.layer];
self.drawCanvas.points = nil;
[self.drawCanvas setNeedsDisplay];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGPoint point = [self getPoint:touches];
[self.drawCanvas.points addObject:[NSValue valueWithCGPoint:point]];
[self.drawCanvas setNeedsDisplay];
}
- (UIImage *)imageFromLayer:(CALayer *)layer
{
UIGraphicsBeginImageContext([layer frame].size);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
#end
drawingView.h
#interface drawingView : UIView
#property (nonatomic, assign) CGPoint startPoint;
#property (nonatomic, strong) NSMutableArray *points;
#end
drawingView.m
#implementation drawingView
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2.0f);
CGContextMoveToPoint(context, self.startPoint.x, self.startPoint.y);
for (NSValue *point in self.points)
{
CGPoint location = [point CGPointValue];
CGContextAddLineToPoint(context, location.x, location.y);
}
CGContextStrokePath(context);
}
#end
I also have "drawingLayer" which is essentially the same thing as "drawingView", except it a subclass of CALayer and does the same drawing in "drawInContext".
What I found was the drawRect has much better performance, the drawing is almost in-sync with the touch position, with very minor lag.
Why is this the case? I expected the CALayer drawing to be at least the same, if not better. In fact, someone told me today that drawing in CALayer is hardware-accelerated, which is the preferred way if performance is a concern. Certainly this is NOT the case in my little experiment. Why?
It might be caused by CALayer's default animation.
Try to override the action(forKey event: String) -> CAAction? and always return nil while subclassing the CALayer Class
I used a solution from this question SpriteKit Objective-C: programming directional pad controls as well as a version of custom class buttons from here Correct way to create button in Sprite Kit? with omitted target-action methods to create virtual control buttons for my SpriteKit game. So here is the problem: what I am trying to implement is two separate sets of buttons unrelated to each other (for instance, D-pad on the left, and fire buttons on the right) and the ability to use them both at the same time with help of multi-touch, just like you would on a hardware controller with action buttons on the right and dirs on the left. So let's imagine the situation:
1) I start by holding a directional button and a fire button. Then I drag my left finger outside the directional button, which triggers the if(node.name)'s ELSE statement, that sets all buttons' "selected" bools to NO. This is not what I want because the fire button is still held, and it should retain it's "selected" state, while directional button — shouldn't.
2) Same situation, but if I drag my right finger outside the fire button instead, and keep holding directional button. Both buttons get "deselected", when fire button shouldn't do it.
So how do I implement it correctly with a way to detect, which button exactly got "deselected" to "deselect" just that particular set of buttons? Please push me in the right direction. Hope what I have requested is possible.
Current code (It's pretty messy, excuse the gorilla-style coding):
DirectionalButton.h
#import <SpriteKit/SpriteKit.h>
#interface DirectionalButton : SKSpriteNode
#property (nonatomic) BOOL isEnabled;
#property (nonatomic) BOOL isSelected;
#property (nonatomic, readonly, strong) SKLabelNode *title;
#property (nonatomic, readwrite, strong) SKTexture *normalTexture;
#property (nonatomic, readwrite, strong) SKTexture *selectedTexture;
#property (nonatomic, readwrite, strong) SKTexture *disabledTexture;
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected;
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected disabled:(SKTexture *)disabled;
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected;
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected disabled:(NSString *)disabled;
#end
DirectionalButton.m
#import "DirectionalButton.h"
#implementation DirectionalButton
#pragma mark Texture Initializer
- (instancetype)initWithTexture:(SKTexture *)texture color:(UIColor *)color size:(CGSize)size {
return [self initWithTextureNormal:texture selected:nil disabled:nil];
}
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected {
return [self initWithTextureNormal:normal selected:selected disabled:nil];
}
- (instancetype)initWithTextureNormal:(SKTexture *)normal selected:(SKTexture *)selected disabled:(SKTexture *)disabled {
self = [super initWithTexture:normal color:[UIColor whiteColor] size:normal.size];
if (self) {
[self setNormalTexture:normal];
[self setSelectedTexture:selected];
[self setDisabledTexture:disabled];
[self setIsEnabled:YES];
[self setIsSelected:NO];
_title = [SKLabelNode labelNodeWithFontNamed:#"Arial"];
[_title setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
[_title setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
[self addChild:_title];
[self setUserInteractionEnabled:YES];
}
return self;
}
#pragma mark Image Initializer
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected {
return [self initWithImageNamedNormal:normal selected:selected disabled:nil];
}
- (instancetype)initWithImageNamedNormal:(NSString *)normal selected:(NSString *)selected disabled:(NSString *)disabled {
SKTexture *textureNormal = nil;
if (normal) {
textureNormal = [SKTexture textureWithImageNamed:normal];
}
SKTexture *textureSelected = nil;
if (selected) {
textureSelected = [SKTexture textureWithImageNamed:selected];
}
SKTexture *textureDisabled = nil;
if (disabled) {
textureDisabled = [SKTexture textureWithImageNamed:disabled];
}
return [self initWithTextureNormal:textureNormal selected:textureSelected disabled:textureDisabled];
}
#pragma -
#pragma mark Setter overrides
- (void)setIsEnabled:(BOOL)isEnabled {
_isEnabled = isEnabled;
if ([self disabledTexture]) {
if (!_isEnabled) {
[self setTexture:_disabledTexture];
} else {
[self setTexture:self.normalTexture];
}
}
}
- (void)setIsSelected:(BOOL)isSelected {
_isSelected = isSelected;
if ([self selectedTexture] && [self isEnabled]) {
if (_isSelected) {
[self setTexture:_selectedTexture];
[self runAction:[SKAction fadeAlphaTo:0.55 duration:0.12f]];
} else {
[self setTexture:self.normalTexture];
[self runAction:[SKAction fadeAlphaTo:1 duration:0.12f]];
}
}
}
#end
GameScene.m
- (void)createHUD {
//Executed in didMoveToView
NSString *pathToImageForLeftButtonTexture = #"buttonDirectionalLeft";
NSString *pathToImageForRightButtonTexture = #"buttonDirectionalRight";
dirBtnLeft = [[DirectionalButton alloc]initWithImageNamedNormal:pathToImageForLeftButtonTexture selected:pathToImageForLeftButtonTexture];
/*
Set size and position for left
*/
dirBtnLeft.name = #"directionalLeft";
dirBtnRight = [[DirectionalButton alloc]initWithImageNamedNormal:pathToImageForRightButtonTexture selected:pathToImageForRightButtonTexture];
/*
Set size and position accordingly to left button for right
*/
dirBtnRight.name = #"directionalRight";
dirBtnLeftFrame = [SKSpriteNode spriteNodeWithColor:[SKColor clearColor] size:dirBtnLeft.size];
dirBtnLeftFrame.position = dirBtnLeft.position;
dirBtnRightFrame = [SKSpriteNode spriteNodeWithColor:[SKColor clearColor] size:dirBtnRight.size];
fireBtn = [[DirectionalButton alloc]initWithImageNamedNormal:#"default.jpg" selected:#"default.jpg"];
/*
Set position and size for fire
*/
fireBtnFrame = [SKSpriteNode spriteNodeWithColor:[SKColor clearColor] size:fireBtn.size];
fireBtnFrame.position = fireBtn.position;
dirBtnRightFrame.position = dirBtnRight.position;
dirBtnLeftFrame.zPosition = 100;
dirBtnRightFrame.zPosition = 100;
fireBtnFrame.zPosition = 100;
dirBtnRight.zPosition = 99;
dirBtnLeft.zPosition = 99;
fireBtn.zPosition = 99;
dirBtnLeftFrame.name = #"directionalLeftFrame";
dirBtnRightFrame.name = #"directionalRightFrame";
fireBtnFrame.name = #"primaryFire";
[self addChild:dirBtnLeft];
[self addChild:dirBtnRight];
[self addChild:dirBtnLeftFrame];
[self addChild:dirBtnRightFrame];
[self addChild:fireBtn];
[self addChild:fireBtnFrame];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesMoved:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
for(UITouch *touch in [event allTouches]){
CGPoint touchLocation = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:touchLocation];
if (node.name)
{
if ([node.name isEqualToString:#"directionalRightFrame"])
{
if(!dirBtnRight.isSelected){
[dirBtnRight setIsSelected:YES];
[dirBtnLeft setIsSelected:NO];}
}
else if ([node.name isEqualToString:#"directionalLeftFrame"])
{
if(!dirBtnLeft.isSelected){
[dirBtnRight setIsSelected:NO];
[dirBtnLeft setIsSelected:YES];}
}
else if ([node.name isEqualToString:#"primaryFire"]) {
if (!fireBtn.isSelected) {
[fireBtn setIsSelected:YES];
}
}
}
else
{
[dirBtnRight setIsSelected:NO];
[dirBtnLeft setIsSelected:NO];
[fireBtn setIsSelected:NO];
}}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in [event allTouches]) {
CGPoint touchPoint = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:touchPoint];
if(node.name){
if ([node.name isEqualToString:#"directionalLeftFrame"]) {
dirBtnLeft.isSelected = NO;}
else if ([node.name isEqualToString:#"directionalRightFrame"])
{
dirBtnRight.isSelected = NO;
}
else if([node.name isEqualToString:#"primaryFire"]){
fireBtn.isSelected = NO;}
} else
{
dirBtnLeft.isSelected = NO;
dirBtnRight.isSelected = NO;
fireBtn.isSelected = NO;}}
}
-(void)update:(CFTimeInterval)currentTime {
if(dirBtnLeft.isSelected){
//Do something
}
else if(dirBtnRight.isSelected){
//Do something else
}
else
{
//Stop doing anything
}
}
In touchesEnded you are looping through all the active touches in the SKScene.
[event allTouches] returns all the active touches.
Instead of that just use the touches NSSet to loop through the touches that have actually ended.
Use the following code instead in touchesMoved and touchesEnded.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
// Your conditions
}
}
I have been following a tutorial on SpriteKit, and for the life of me, I don't know where this one method comes from. In a StartGameLayer, I have this code in its entirety:
#import "StartGameLayer.h"
#interface StartGameLayer()
#property (nonatomic, retain) SKSpriteNode* playButton;
#end
#implementation StartGameLayer
- (id)initWithSize:(CGSize)size
{
if(self = [super initWithSize:size])
{
SKSpriteNode* startGameText = [SKSpriteNode spriteNodeWithImageNamed:#"FlappyBirdText"];
startGameText.position = CGPointMake(size.width * 0.5f, size.height * 0.8f);
[self addChild:startGameText];
SKSpriteNode* playButton = [SKSpriteNode spriteNodeWithImageNamed:#"PlayButton"];
playButton.position = CGPointMake(size.width * 0.5f, size.height * 0.30f);
[self addChild:playButton];
[self setPlayButton:playButton];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if ([_playButton containsPoint:location])
{
if([self.delegate respondsToSelector:#selector(startGameLayer:tapRecognizedOnButton:)])
{
[self.delegate startGameLayer:self tapRecognizedOnButton:StartGameLayerPlayButton];
}
}
}
#end
Where does the setPlayButton:(SKSpriteNode* ) method get set? In the help file it says it is declared in this file, but this is the only instance I see of it, and it is just driving me the tiniest bit nuts how this method is created.
Im trying to get simultaneous pan and pinch from the article below but i dont think the delegate is hooked up properly since im seeing no effect. Right now I have a pan and a pinch gesture recognizer that both work. I make IBOutlets to my viewcontroller, and in my viewController initializer have:
EDIT
here is the header and implementation files respectively.
header:
#import <UIKit/UIKit.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#class GLView;
#interface GLViewController : UIViewController <UIGestureRecognizerDelegate>
#property (strong, nonatomic) IBOutlet UIPinchGestureRecognizer *pinchRecognizer;
#property (strong, nonatomic) IBOutlet UIPanGestureRecognizer *panRecognizer;
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer;
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer;
- (void)drawView:(GLView*)view;
- (void)setupView:(GLView*)view;
#property (retain, nonatomic) IBOutlet UILabel *zoomFactorLabel;
#property (retain, nonatomic) IBOutlet UILabel *xPosLabel;
#property (retain, nonatomic) IBOutlet UILabel *yPosLabel;
#end
panRecognizer.minimumNumberOfTouches = 1;
panRecognizer.delegate = self; // Very important
pinchRecognizer.delegate = self; // Very important
implementation:
#import "GLViewController.h"
#import "GLView.h"
#import "OpenGLCommon.h"
#import "ConstantsAndMacros.h"
#import "TileManager.h"
#import <CoreGraphics/CoreGraphics.h>
#implementation GLViewController
#synthesize pinchRecognizer;
#synthesize panRecognizer;
#synthesize zoomFactorLabel;
#synthesize xPosLabel;
#synthesize yPosLabel;
TileManager* tileManager;
CGPoint currentPosition;
CGPoint start;
CGFloat temp = 0;
CGFloat x=0;
CGFloat y=0;
CGFloat mLastScale=1;
CGFloat mCurrentScale=1;
CGPoint translation;
- (id) init {
self = [super init];
if (self != nil) {
printf("GLViewController initialized.");
tileManager=[[TileManager alloc] init];
currentPosition = CGPointMake(0, 0);
}
return self;
}
CGFloat scale=1;
CGPoint position;
CGPoint mid;
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
NSLog(#"delegate called");
// If you have multiple gesture recognizers in this delegate, you can filter them by comparing the gestureRecognizer parameter to your saved objects
return YES; // Also, very important.
}
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer {
scale=scale*recognizer.scale;
mCurrentScale += [recognizer scale] - mLastScale;
mLastScale = [recognizer scale];
if (recognizer.state == UIGestureRecognizerStateBegan)
{
//get midpoint
CGPoint zero=[recognizer locationOfTouch:0 inView:self.view];
CGPoint one=[recognizer locationOfTouch:1 inView:self.view];
float x=zero.x+one.x;
float y=zero.y+one.y;
mid.x=x/2;
mid.y=y/2;
}
else if (recognizer.state == UIGestureRecognizerStateEnded)
{
mLastScale = 1.0;
}
NSString *xPosString = [NSString stringWithFormat:#"%.2f",mid.x];
NSString *yPosString = [NSString stringWithFormat:#"%.2f",mid.y];
xPosLabel.text=xPosString;
yPosLabel.text=yPosString;
}
- (IBAction)handlePan:(UIPanGestureRecognizer* )recognizer {
[recognizer setMaximumNumberOfTouches:1];
translation= [recognizer translationInView:self.view];
NSString *xPosString = [NSString stringWithFormat:#"%.2f",currentPosition.x];
NSString *yPosString = [NSString stringWithFormat:#"%.2f",currentPosition.y];
xPosLabel.text=xPosString;
yPosLabel.text=yPosString;
currentPosition.x=currentPosition.x+translation.x;
currentPosition.y=currentPosition.y+translation.y;
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
- (void)drawView:(GLView*)view
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(mid.x, -mid.y, 0);
glScalef(mCurrentScale,mCurrentScale, 0);
glTranslatef(-mid.x, mid.y, 0);
glTranslatef(currentPosition.x,currentPosition.y*-1,0);
[tileManager drawView:view];
//draw calls
}
-(void)setupView:(GLView*)view
{
CGRect rect = view.bounds;
glViewport(0, 0,rect.size.width,rect.size.height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(0,(rect.size.width),-(rect.size.height),0, -1, 1 ) ;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0,1,1, 1);
// Enable Smooth Shading, default not really needed.
glShadeModel(GL_SMOOTH);
// Depth buffer setup.
glClearDepthf(1.0f);
//enable textures.
glEnable(GL_TEXTURE_2D);
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_FASTEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
[tileManager setupView:view];
}
- (void)viewDidLoad
{
[super viewDidLoad];
panRecognizer.delegate=self;
pinchRecognizer.delegate=self;
NSLog(#"pan recognizer delegate [%#]", [panRecognizer.delegate description]);
}
- (void)viewDidUnload {
[self setPinchRecognizer:nil];
[self setPanRecognizer:nil];
[super viewDidUnload];
}
#end
a NSLog is in the body of the delegate method but never gets executed. Any help is appreciated.
article
If the view controller is loaded from the interface builder, then the initializer is the wrong place to set that stuff up. Do it in -viewDidLoad.
you probably caught it by now - but it seems that you miss a space in the delegate:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldRecognizeSimultaneouslyWithGestureRecognizer
to
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer
So, I added a popupview to my uisliders. I got the code for the custom sliders with the popup from a guy who had already done that. The popup is showing, but the only problem is that the popup is showing inside the cell in which the slider is at, so it gets cut off at the end of the cell.
How can I bring the popupview in front of the cell ?
(I have multiple sliders each one in a different cell)
#import "MNEValueTrackingSlider.h"
#import "ToothTableViewController.h"
#pragma mark - Private UIView subclass rendering the popup showing slider value
#interface MNESliderValuePopupView : UIView {
MNEValueTrackingSlider *trackingSlider;
ToothTableViewController *toothViewController;
}
#property (nonatomic) float value;
#property (nonatomic, retain) UIFont *font;
#property (nonatomic, retain) NSString *text;
#end
#import "MNEValueTrackingSlider.h"
#import "ToothTableViewController.h"
#implementation MNESliderValuePopupView
#synthesize value=_value;
#synthesize font=_font;
#synthesize text = _text;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.font = [UIFont boldSystemFontOfSize:18];
}
return self;
}
- (void)dealloc {
self.text = nil;
self.font = nil;
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
// Set the fill color
[[UIColor colorWithWhite:0 alpha:0.8] setFill];
// Create the path for the rounded rectanble
CGRect roundedRect = CGRectMake(self.bounds.origin.x , self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height * 0.8);
UIBezierPath *roundedRectPath = [UIBezierPath bezierPathWithRoundedRect:roundedRect cornerRadius:6.0];
// Create the arrow path
UIBezierPath *arrowPath = [UIBezierPath bezierPath];
CGFloat midX = CGRectGetMidX(self.bounds);
CGPoint p0 = CGPointMake(midX, CGRectGetMaxY(self.bounds));
[arrowPath moveToPoint:p0];
[arrowPath addLineToPoint:CGPointMake((midX - 10.0), CGRectGetMaxY(roundedRect))];
[arrowPath addLineToPoint:CGPointMake((midX + 10.0), CGRectGetMaxY(roundedRect))];
[arrowPath closePath];
// Attach the arrow path to the buble
[roundedRectPath appendPath:arrowPath];
[roundedRectPath fill];
// Draw the text
if (self.text) {
[[UIColor colorWithWhite:1 alpha:0.8] set];
CGSize s = [_text sizeWithFont:self.font];
CGFloat yOffset = (roundedRect.size.height - s.height) / 2;
CGRect textRect = CGRectMake(roundedRect.origin.x, yOffset, roundedRect.size.width, s.height);
[_text drawInRect:textRect
withFont:self.font
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentCenter];
}
}
- (void)setValue:(float)aValue {
_value = aValue;
self.text = [NSString stringWithFormat:#"%4.2f", _value];
[self setNeedsDisplay];
}
#end
#pragma mark - MNEValueTrackingSlider implementations
#import "ToothTableViewController.h"
#implementation MNEValueTrackingSlider
#synthesize thumbRect;
#synthesize sliderButtonPoint;
#pragma mark - Private methods
- (void)_constructSlider {
valuePopupView = [[MNESliderValuePopupView alloc] initWithFrame:CGRectZero];
valuePopupView.backgroundColor = [UIColor clearColor];
valuePopupView.alpha = 0.0;
toothViewController = [[ToothTableViewController alloc] init];
[self addSubview:valuePopupView];
}
- (void)_fadePopupViewInAndOut:(BOOL)aFadeIn {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
if (aFadeIn) {
valuePopupView.alpha = 1.0;
} else {
valuePopupView.alpha = 0.0;
}
[UIView commitAnimations];
}
- (void)_positionAndUpdatePopupView {
CGRect _thumbRect = self.thumbRect;
CGRect popupRect = CGRectOffset(_thumbRect, 0, -(_thumbRect.size.height * 1.5));
valuePopupView.frame = CGRectInset(popupRect, -20, -10);
valuePopupView.value = (NSInteger)self.value;
}
#pragma mark - Memory management
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self _constructSlider];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self _constructSlider];
}
return self;
}
- (void)dealloc {
[valuePopupView release];
[super dealloc];
}
#pragma mark - UIControl touch event tracking
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
// Fade in and update the popup view
CGPoint touchPoint = [touch locationInView:self];
// Check if the knob is touched. Only in this case show the popup-view
if(CGRectContainsPoint(self.thumbRect, touchPoint)) {
[self _positionAndUpdatePopupView];
[self _fadePopupViewInAndOut:YES];
}
return [super beginTrackingWithTouch:touch withEvent:event];
}
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
// Update the popup view as slider knob is being moved
[self _positionAndUpdatePopupView];
return [super continueTrackingWithTouch:touch withEvent:event];
}
- (void)cancelTrackingWithEvent:(UIEvent *)event {
[super cancelTrackingWithEvent:event];
}
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
// Fade out the popoup view
[self _fadePopupViewInAndOut:NO];
[super endTrackingWithTouch:touch withEvent:event];
}
#pragma mark - Custom property accessors
- (CGRect)thumbRect {
CGRect trackRect = [self trackRectForBounds:self.bounds];
CGRect thumbR = [self thumbRectForBounds:self.bounds
trackRect:trackRect
value:self.value];
return thumbR;
}
#end
Ok so I gave up, I cant figure it out. That is the code for the slider and its popupview. If anyone feels like reading the whole thing I could use the help :P
You could try to add the popupview as a subview of the UITableView.
Then to move it along with the slider, you would have to calculate the point by getting the slider's position relative to your tableview.
This can be achieved by using the UIView's convertPoint:toView: method, for example:
CGPoint sliderButtonRelativePoint = [slider.superview convertPoint:sliderButtonPoint toView:tableView];
where slider.superview would be your UITableViewCell, sliderButtonPoint would be the middle-top point of the slider's round button (for example), and tableView would be, well... your UITableView.
You might have to play around with this a little, and you may find there are strange behaviours when scrolling the tableview, but that's what I would try first.