implementing a UIGestureRecognizerDelegate - ios

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

Related

How I rotate an image with swipe gesture from an anchor point in objective c?

Here,I rotate an image given angle. But I want to rotate an image with swipe gesture from an anchor point.Here is my code..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//circleName is an UIImageView IBoutlet
_circleNames=#"Squre.png";
_showCircle=[UIImage imageNamed:_circleNames];
_circleView.image=_showCircle;
// Here I am setting anchor point
_circleView.layer.anchorPoint=CGPointMake(0.5, 1.0);
//here I am setting animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:6];
[UIView setAnimationRepeatCount:0];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
//rotate 170 degree angle
_circleView.transform=CGAffineTransformRotate(_circleView.transform,170);
[UIView commitAnimations];
}
if you want to dynamically rotate image following your finger you must use UIPanGestureRecognizer (not UISwipeGestureRecognizer). It gives you point of your finger in repeatedly called selector you provide.
UPDATE:
You can use this code:
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIView* rotView;
#end
#implementation ViewController {
UIPanGestureRecognizer* _panGesture;
float _deltaAngle;
CGAffineTransform _startTransform;
CGPoint _prevPoint;
}
- (void) viewDidLoad {
[super viewDidLoad];
_panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(rotateItem:)];
_panGesture.delegate = self;
[self.rotView addGestureRecognizer:_panGesture];
}
- (void) rotateItem:(UIPanGestureRecognizer *)recognizer {
CGPoint currPoint = [recognizer locationInView:self.view];
CGPoint center = recognizer.view.center;
CGFloat ang = atan2f(currPoint.y - center.y, currPoint.x - center.x) - atan2f(_prevPoint.y - center.y, _prevPoint.x - center.x);
_prevPoint = [recognizer locationInView:self.view];
_deltaAngle += ang;
self.rotView.transform = CGAffineTransformRotate(_startTransform, _deltaAngle);
}
- (BOOL) gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)recognizer {
_startTransform = self.rotView.transform;
return YES;
}
#end
UPDATE2
I've created class (and category) with sample on github:
https://github.com/faviomob/UIRotatableView
You can use this to rotate your image 90degrees.
CGAffineTransformMakeRotation(CGFloat(M_PI_2))

How to detect touch on non-transparent parts of overlay image drawn by MKOverlayRenderer

I draw an image on my map as overlay like so (RW example code):
It has a transparent part in the middle (that should let touches through) and non-transparent sides that should catch touches (kind of like a donut :)).
Overlay.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#class PVPark;
#interface PVParkMapOverlay : NSObject <MKOverlay>
- (instancetype)initWithPark:(PVPark *)park;
#end
Overlay.m
#import "PVParkMapOverlay.h"
#import "PVPark.h"
#implementation PVParkMapOverlay
#synthesize coordinate;
#synthesize boundingMapRect;
- (instancetype)initWithPark:(PVPark *)park {
self = [super init];
if (self) {
boundingMapRect = park.overlayBoundingMapRect;
coordinate = park.midCoordinate;
}
return self;
}
#end
OverlayView.h
#import <MapKit/MapKit.h>
#interface PVParkMapOverlayView : MKOverlayRenderer
- (instancetype)initWithOverlay:(id<MKOverlay>)overlay overlayImage:(UIImage *)overlayImage;
#end
OverlayView.m
#import "PVParkMapOverlayView.h"
#interface PVParkMapOverlayView ()
#property (nonatomic, strong) UIImage *overlayImage;
#end
#implementation PVParkMapOverlayView
- (instancetype)initWithOverlay:(id<MKOverlay>)overlay overlayImage:(UIImage *)overlayImage {
self = [super initWithOverlay:overlay];
if (self) {
_overlayImage = overlayImage;
}
return self;
}
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
CGImageRef imageReference = self.overlayImage.CGImage;
MKMapRect theMapRect = self.overlay.boundingMapRect;
CGRect theRect = [self rectForMapRect:theMapRect];
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0.0, -theRect.size.height);
CGContextDrawImage(context, theRect, imageReference);
}
#end
I add it to the map like so:
MainViewController
- (void) viewDidLoad
{
[super viewDidLoad];
[self addOverlay];
}
- (void)addOverlay {
PVParkMapOverlay *overlay = [[PVParkMapOverlay alloc] initWithPark:self.park];
[self.mapView addOverlay:overlay];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
if ([overlay isKindOfClass:PVParkMapOverlay.class]) {
UIImage *magicMountainImage = [UIImage imageNamed:#"overlay_park"];
PVParkMapOverlayView *overlayView = [[PVParkMapOverlayView alloc] initWithOverlay:overlay overlayImage:magicMountainImage];
return overlayView;
}
return nil;
}
How can I detect a touch on the non-transparent part of the overlayed image? I've tried using some examples using MKPolyLines but to no avail. Should I create an invisible (to the user) polyline using the cutout's location data and check for that? Seems like there should be a way to catch the overlay more efficiently, no?

Correct way to create button in Sprite Kit?

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)

Calling a superclasses designated initialiser calls the subclasses

I have what seems like a straightforward enough issue, but I just have no idea why it's working the way it is.
I have a class Shape which has a subclass of Square.
When I call Square and call its designated initialiser, in self = [super init] it calls the super class. However when the superclass calls its designated initialiser, named the same as one of the subclasses, it calls the subclass.
What I end up with is an infinite loop of the subclass calling init on the superclass and that calling the subclasses initialiser.
How can I solve this issue? Should I make sure the names of my initialisers are different enough so this can't happen?
Shape.h
#import <Foundation/Foundation.h>
#interface Shape : NSObject
#property (nonatomic) CGPoint position;
#property (nonatomic) float width;
#property (nonatomic) float height;
#property (nonatomic, readonly) float area;
- (id)initWithWidth:(float)width andHeight:(float)height andPosition:(CGPoint)position;
- (id)initWithWidth:(float)width andHeight:(float)height;
- (id)initWithWidth:(float)width;
- (id)init;
- (NSString *)drawShape;
#end
-
Shape.m
#import "Shape.h"
#implementation Shape
- (id)initWithWidth:(float)width andHeight:(float)height andPosition:(CGPoint)position
{
self = [super init];
if (self) {
self.width = width;
self.height = height;
self.position = position;
}
return self;
}
- (id)initWithWidth:(float)width andHeight:(float)height
{
return [self initWithWidth:width andHeight:height andPosition:CGPointMake(100, 100)];
}
- (id)initWithWidth:(float)width
{
return [self initWithWidth:width andHeight:1.0f andPosition:CGPointMake(100, 100)];
}
- (id)init
{
CGPoint defaultPoint = CGPointMake(100, 100);
return [self initWithWidth:1.0 andHeight:1.0 andPosition:defaultPoint];
}
- (NSString *)drawShape
{
NSString *outputShape = [NSString stringWithFormat:#"Drawing shape - (%.2f,%.2f), width - %f, height - %f", self.position.x, self.position.y, self.width, self.height];
NSLog(#"%#", outputShape);
return outputShape;
}
#end
-
Square.h
#import <Foundation/Foundation.h>
#import "Shape.h"
#interface Square : Shape
- (id)initWithWidth:(float)width andPosition:(CGPoint)position;
- (id)initWithWidth:(float)width andHeight:(float)height andPosition:(CGPoint)position;
- (id)initWithWidth:(float)width andHeight:(float)height;
- (id)initWithWidth:(float)width;
#end
-
Square.m
#import "Square.h"
#implementation Square
- (id) initWithWidth:(float)width andPosition:(CGPoint)position
{
self = [super init];
if (self) {
self.width = width;
self.height = width;
self.position = position;
}
return self;
}
// Returning the width as the width and height as you can't make a square with different sides
- (id)initWithWidth:(float)width andHeight:(float)height andPosition:(CGPoint)position
{
return [self initWithWidth:width andPosition:position];
}
- (id)initWithWidth:(float)width andHeight:(float)height
{
return [self initWithWidth:width andPosition:CGPointMake(100, 100)];
}
- (id)initWithWidth:(float)width
{
return [self initWithWidth:width andPosition:CGPointMake(100, 100)];
}
- (NSString *)drawShape
{
NSString *outputShape = [NSString stringWithFormat:#"Drawing shape - (%.2f,%.2f), width - %.2f, height - %.2f", self.position.x, self.position.y, self.width, self.height];
NSLog(#"%#", outputShape);
return outputShape;
}
#end
The thing to do here is to reimplement -[Square initWithWidth:andPosition:] like:
- (id)initWithWidth:(float)width andPosition:(CGPoint)position
{
self = [super initWithWidth:width andHeight:width andPosition:position];
return self;
}

Bringing PopUpView in front of a cell

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.

Resources