Thursday, 7 February 2013

Star Rating in iPhone using UITouch




If you have an application in which you want to take user reviews and want to provide a star rating, you are in a big trouble cause Cocoa Touch (iPhone) does not provide any UIControl for it.
You have to create your own control for this using touch detection or gesture recognition.

In following tutorial i have detected point of touch for achieving my goal.

1. Here i have added a UIView - viewForStarRating on which i placed 5 UIImageViews - imgViewStar1, imgViewStar2, imgViewStar3, imgViewStar4 and imgViewStar5 on my Nib file and set outlet to each.
2. Declare two CGPoints - touchStartPoint and touchCurrentPoint, these CGPoints will give me my touch coordinates.
3. In my implementation file i added touchesBegan and touchesMoved delegate methods.
4. In touchesBegan delegate :
   UITouch *touch = [touches anyObject];
   self.touchStartPoint = [touch locationInView:self.viewForStarRating];
   NSLog(@"Touch detected at: x = %f and y = %f",self.touchStartPoint.x,self.touchStartPoint.y);

5. This self.touchStartPoint.x and self.touchStartPoint.y will give me my initial x & y coordinates of touch in self.viewForStarRating.
6.  In touchesMoved delegate :
        UITouch *touch = [touches anyObject];
    self.touchCurrentPoint = [touch locationInView:self.viewForStarRating];
    
    //NSLog(@"Touch is currently at: x = %f and y = %f",self.touchCurrentPoint.x,self.touchCurrentPoint.y);
    int leftSpace = 20;
    if (self.touchCurrentPoint.x <= leftSpace + 5) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarEmpty.png"]];
    } else if (self.touchCurrentPoint.x >= leftSpace + 15 && self.touchCurrentPoint.x <= leftSpace + 25) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarHalf.png"]];
    } else if (self.touchCurrentPoint.x >= leftSpace + 35) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarFull.png"]];
    }
7. As you can see in above point i have taken a leftSpace which is nothing but the padding space between x coordinate of self.viewForStarRating and self.imgViewStar1.
8. Above code will detect the touch points and will act by changing image in self.imgViewStar1.
9. I just applied a simple logic that if a user slides and leaves touch at initial point (in my case 5 px of self.imgViewStar1), set an empty star image.
10. If user slides till centre (in my case 15 to 25 px of self.imgViewStar1), set a half filled star image.
11. If user slides to end of star (in my case 35px of self.imgViewStar1), set full filled star image.









You can download sample code here: Star Rating