In an update I have planned for one of my apps, I had a need to develop a 5-star rating view so people could rate items they make with the app.
As I was working on this control, I thought this might make a good tutorial – especially since it would fit in well with our previous tutorial on how to rate babes with Facebook ;]
So in this tutorial, we’ll go through a short example of making a 5-star rating control and in the process we’ll learn the ropes of creating custom UIViews in general.
Let’s dive right in by creating a new project with the iOS\Application\Single View Application template and name it CustomView. Make sure the Device Family is set to iPhone, Use Storyboard and Use Automatic Reference Counting are checked, and click Next.
Now create a new file with the iOS\Cocoa Touch\Objective C class template. Enter RateView for the Class name, and UIView for Subclass of.
Next, let’s fill in our header file. Replace the contents of RateView.h with the following:
First we set up a delegate so we can notify our view controller when the rating changes. We could have done this via blocks or a target/selector as well, but I thought this was simpler.
Next, we set up a bunch of properties:
Three UIImages to represent not selected, half selected, and fully selected.
A variable to keep track of our current rating.
A boolean to keep track of whether this view should be editable or not. For example, sometimes we may wish to just display a rating without letting the user edit it.
An array to keep track of the image views we’ll have as children of this view. Note we could have implemented this by just drawing the images in drawRect, but this was simpler (albeit slower performance).
The maximum value for a rating. This actually allows us to support other numbers of stars than 5 – for example, maybe we want 3 stars, or 10 stars? Also note the minimum is an assumed 0.
Variables to keep track of spacing in case our user wants to change it: the margin between images, the left margin, and a minimum image size.
Finally a variable to keep track of our delegate.
Initialization and Cleanup
Next, we add in the boilerplate code for the construction of our classes. Replace RateView.m with the following:
This is all pretty boilerplate stuff where we initialize our instance variables to default values. Note that we support both initWithFrame and initWithCoder so that our view controller can add us via a XIB or programatically.
Refreshing Our View
Pretend that the view controller has set up our instance variables with valid images, ratings, maxRating, etc, and that we’ve created our UIImageView subviews. Well we need to write a method to refresh the display based on the current rating. Add this method to the file next:
Pretty simple stuff here – we just loop through our list of images and set the appropriate image based on the rating.
Probably the most important function in our file is the implementation of layoutSubviews. This function gets called whenever the frame of our view changes, and we’re expected to set up the frames of all of our subviews to the appropriate size for that space. So add this function next:
We first bail if our notSelectedImage isn’t set up yet.
But if it is, we just do some simple calculations to figure out how to set the frames for each UIImageView.
The images are laid out like the following to fill the entire frame: left margin, image #1, mid margin, …, image #n, left margin.
So if we know the full size of the frame, we can subtract out the margins and divide by the number of images to figure out how wide to make each of the UIImageViews.
Once we know that, we simply loop through and update the frames for each UIImageView.
Since we don’t know the order in which the view controller is going to set our properties (especially since they could even change mid-display), we have to be careful about how we construct our subviews, etc. This is the approach I took to solve the problem, if anyone else has a different approach I’d love to hear!
The most important method is the setMaxRating method – because this determines how many UIImageView subviews we have. So when this changes, we remove any existing image views and create the appropriate amount. Of course, once this happens we need to make sure layoutSubviews and refresh is called, so we call setNeedsLayout and refresh.
Similarly, when any of the images or the rating changes, we need to make sure our refresh method gets called so our display is consistent.
Finally the fun stuff: touch detection! Add this to the bottom of your file:
Our main code is in handleTouchAtLocation, the rest of the methods either call this or notify our delegate that something has changed.
In handleTouchAtLocation, we simply loop through our subviews (backwards) and compare the x coordinate to that of our subviews. If the x coordinate is greater than the current subview, we know the rating is the index of the subview+1.
Note this doesn’t support “half-star” ratings but could easily be modified to do so.
Using the 5 Star Rating View
Now finally time to try this out! Open MainStoryboard.storyboard and go to Editor\Canvas\Show Bounds Rectangles (this will make it easier to see what we’re doing).
Then drag a UIView and a UILabel from the Object Library into the view controller, and resize them to look like the following:
Then click on the UIView you added and go to the Identity Inspector. Set the class to RateView:
Now let’s connect these to outlets. Bring up the Assistant editor, and make sure that ViewController.h is visible. Control-drag from the UIView down between the @interface and @end lines, and connect it to an Outlet named rateView.
Repeat this for the label, but connect it to an outlet called statusLabel.
We want to make the View Controller implement the RateViewDelegate protocol, so also import the RateViewHeader and mark it as doing so. At this point ViewController.h should look like the following: