Search code examples
iphoneiosuislider

how to increase and decrease circle size in uislider with value change


I want to increase and decrease a circle size in uislider with value change..

here my code

draw.m

- (id)initWithFrame:(CGRect)frame value:(float )x
{
    value=x;
    self = [super initWithFrame:frame];
    if (self) {

    }
   return self;
 }

- (void)drawRect:(CGRect)rect{

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGRect rectangle = CGRectMake(6,17,value,value);
CGContextAddEllipseInRect(context, rectangle);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillPath(context);

}

and ViewController.m

@implementation ViewController
 @synthesize mySlider,colorLabel;

 - (void)viewDidLoad
  {    [super viewDidLoad];
  }

  - (void)didReceiveMemoryWarning
 {
 [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
 -(IBAction)sliderValue:(UISlider*)sender
{

float r=[[NSString stringWithFormat:@"%.0f",mySlider.value] floatValue];
NSLog(@"value...%f",r);
CGRect positionFrame = CGRectMake(10,100,200,100);
circle = [[draw alloc] initWithFrame:positionFrame value:r];
circle.backgroundColor=[UIColor clearColor];
[self.view addSubview:circle];


 }

in this code, circle size has increase but not decrease and another problem is circle look , output is .

enter image description here


Solution

  • Ok, your code works, it just doesn't look like it. Add

    [circle removeFromSuperview];
    circle = nil;
    

    right above

    circle = [[draw alloc] initWithFrame:positionFrame value:r];

    You keep drawing new circles on top of the previous ones so it takes that odd shape and also doesn't look like it's decreasing.

    EDIT

    To redraw your circle instead of creating a new one everytime, as @Larme pointed out, you would have to change your 'draw' object to contain a public method which reassigns your 'draw' circle objects diameter.

    -(void) setDiameterWithFloat: (float)x{
    
        value = x;
    
    }
    

    Then in your sliderValue IBAction, call this new method to assign the new diameter based on your slider and redraw the circle with setNeedsDisplay:

    [circle setDiameterWithFloat:mySlider.value];
    [circle setNeedsDisplay];
    

    This allows you to move your initialization of the object to viewDidLoad in your ViewController, where it will be created and loaded only one time along with the rest of the view.