Skip to content

Instantly share code, notes, and snippets.

@C4Code
Created January 24, 2013 22:49
Show Gist options
  • Save C4Code/4629043 to your computer and use it in GitHub Desktop.
Save C4Code/4629043 to your computer and use it in GitHub Desktop.
Example of a custom slider. You can copy the contents of C4WorkSpace, and then drag / drop the other two files into your project.
//
// Slider.h
//
// Created by Travis Kirton.
//
#import "C4WorkSpace.h"
#import "Slider.h"
@implementation C4WorkSpace {
Slider *s1, *s2;
}
-(void)setup {
CGPoint newCenter = self.canvas.center;
newCenter.y -= 100;
s1 = [[Slider alloc] initWithFrame:CGRectMake(0, 0, 500, 10)];
[s1 rect:s1.frame];
s1.center = newCenter;
[self.canvas addShape:s1];
[self listenFor:@"valueChanged" fromObject:s1 andRunMethod:@"updateSlider2"];
newCenter.y += 100;
s2 = [[Slider alloc] initWithFrame:CGRectMake(0, 0, 500, 10)];
[s2 rect:s2.frame];
s2.center = newCenter;
[self.canvas addShape:s2];
[self listenFor:@"valueChanged" fromObject:s2 andRunMethod:@"updateSlider1"];
}
-(void)updateSlider1 {
s1.value = [C4Math tan:s2.value];
}
-(void)updateSlider2 {
s2.value = [C4Math tan:s1.value];
}
@end
//
// Slider.h
//
// Created by Travis Kirton.
//
#import "C4Shape.h"
@interface Slider : C4Shape
@property (readwrite, nonatomic) CGFloat value;
@end
//
// Slider.h
//
// Created by Travis Kirton.
//
#import "Slider.h"
@implementation Slider {
C4Shape *sliderButton;
CGFloat minX, maxX;
BOOL isSetup;
}
-(void)setup {
if(!isSetup) {
sliderButton = [C4Shape rect:CGRectMake(0, 0, 44, 44)];
minX = sliderButton.center.x+(self.height-44)/2;
maxX = self.width - minX;
sliderButton.center = CGPointMake(minX ,self.height / 2.0);
[self addShape:sliderButton];
sliderButton.userInteractionEnabled = NO;
}
isSetup = YES;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint p = [[touches anyObject] locationInView:self];
p.x = [C4Math constrain:p.x min:minX max:maxX];
p.y = sliderButton.center.y;
if(p.x != sliderButton.center.x) {
sliderButton.center = p;
_value = (sliderButton.center.x - minX)/(maxX - minX);
[self postNotification:@"valueChanged"];
}
}
-(void)setValue:(CGFloat)value {
value = [C4Math constrainf:value min:0 max:1];
if(_value != value) {
_value = value;
CGPoint newCenter = sliderButton.center;
newCenter.x = _value * (maxX - minX) + minX;
sliderButton.center = newCenter;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment