Question

I am taking the free Stanford course on iTunesU(193P) and we created setting up a class that is a subclass of UIView and created a public property called scale. The idea was that when we pinch, the scale of the view is changed accordingly but I am confused about when the setter of the property scale gets called. here is the relevant code below:

@interface FaceView : UIView

@property (nonatomic) CGFloat scale; //anyone who wants do publicly can set my scale

-(void)pinch:(UIPinchGestureRecognizer *)gesture;

@end
@synthesize scale = _scale;

#define DEFAULT_SCALE 0.90

-(CGFloat)scale{
    if(!_scale){
        return DEFAULT_SCALE;
    }else {
        return _scale;
    }
}

-(void)setScale:(CGFloat)scale{
    NSLog(@"setting the scale");
    if(scale != _scale){
        _scale = scale;
        [self setNeedsDisplay];
    }
}

-(void)pinch:(UIPinchGestureRecognizer *)gesture{

    if ( (gesture.state == UIGestureRecognizerStateChanged) || (gesture.state == UIGestureRecognizerStateEnded)){

        self.scale *= gesture.scale;
        gesture.scale = 1;
    }
}

When I am in "pinch mode" the setScale method continues to be called as I am pinching as my NSLog statement prints out until I stop the pinch. When or how does the setScale method continued to be called when there isn't any code programmatically calling it? Perhaps I missed something along the way here.

Was it helpful?

Solution

@cspam, remember that to set the gesture recognizer is 2 steps:
1) Adding a gesture recognizer to UIView - This kind of confused me in the lecture but eventhough he is saying add a gesture recognizer to UIView, he really means add a gesture recognizer FOR UIView, IN UIViewController. That is the code that you are missing that you have to add in the UIViewController subclass in this case (the Faceviewcontroller - your name might be different) and that is what will keep calling your pinch method in FaceView above:

 UIPinchGestureRecognizer *pinchGesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self.faceView action:@selector(pinch)];  
[self.faceView addGestureRecognizer:pinchGesture];

You would add this code in your UIViewController (subclass) in the setter method of your UIView [in other words, create and connect an IBOutlet property in your UIViewController to your UIView in the storyboard] and override the setter method to include the code above.

2) The second part is what you have in your code. So pinch method will be called everytime the controller senses a pinch gesture.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top