Search code examples
iphonetitaniumappcelerator-mobile

How to create a star rating control for an iPhone app using Titanium?


I'm building an iPhone app using the Titanium framework. I need a 5-star rating control in my app, just like the one found in the app store. As a temporary solution I'm using the slider for adding a rating. Most of the examples I found on the web are in objective C. can somebody guide me on achieving this using titanium.

Regards


Solution

  • You just need to create a view and populate it with the number of buttons you want then assign a click event to them.

    var rateView = Ti.UI.createView(),
        max = 5, min = 1; // used in the flexMin and flexMax
    
    function rate(v) {
        // rate code storage goes here
        // your choice on if you want to have separate images of each rating or run a loop
        // based on the value passed in to change a set number of stars to their alternate 
        // image
    }
    
    var flexMin = Ti.UI.createButton({
        systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE,
        top: 0, left: 0,
        height:  rateView.height
    });
    
    flexMin.addEventListener('click', function(e) {
        rate(min);
    });
    
    var flexMax  = Ti.UI.createButton({
        systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
        top: 0, right: 0,
        height:  rateView.height
    });
    
    flexMax.addEventListener('click', function(e) {
        rate(max);
    });
    
    rateView.add(flexMin);
    rateView.add(flexMax); 
    
    var stars = [];
    for(var i=1;i<max;i++) {
        stars[i] = Ti.UI.createButton({
            // styling including the darker or light colored stars you choose,
            'rating': i
        });
        stars[i].addEventListener('click', function(e) {
            rate(e.source.i);
        });   
    }
    

    Using that logic approach above you should be able to change max to set the number of stars you want and simply setup the rate(v) to do one of the two options in the comments above. Keep in mind that you need to add the stars[i] to the view with a left or some type of positing that increments based on the number of stars available. Hope this helps.