Created
November 28, 2015 05:45
-
-
Save mingsai/2dc3cac49418d0d5788f to your computer and use it in GitHub Desktop.
Star Rating Control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MNGStarRating.swift | |
// CommonCents | |
// | |
// Created by Tommie N. Carter, Jr., MBA on 11/27/15. | |
// Copyright © 2015 MING Technology. All rights reserved. | |
// | |
import UIKit | |
/* | |
Usage: On Controller ~> | |
@IBOutlet var ratingHeader: MNGStarRating! { | |
didSet { | |
ratingHeader.ratingDelegate = self | |
} | |
} | |
//within delegate methods: ratingWasChanged | |
self.ratingButton.setTitle(self.starRatingOutlet.starTitle(), forState: UIControlState.Normal) | |
*/ | |
protocol MNGStarRatingDelegate { | |
func ratingWasChanged(value:Float?) | |
} | |
class MNGStarRating: UIView { | |
//MARK: Outlets | |
@IBOutlet var starCollection:[UIButton]! | |
//MARK: Class Properties | |
var ratingDelegate:MNGStarRatingDelegate? = nil | |
private var starRating:Float = 0.0 | |
//MARK: View Lifecycle | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
loadDefaultRatingImages() | |
} | |
/* | |
// Only override drawRect: if you perform custom drawing. | |
// An empty implementation adversely affects performance during animation. | |
override func drawRect(rect: CGRect) { | |
// Drawing code | |
} | |
*/ | |
//MARK: Helper Methods | |
func loadDefaultRatingImages() { | |
for b in starCollection { | |
switch b.tag { | |
case 1: | |
b.setBackgroundImage(UIImage(named: "star1"), forState: .Highlighted) | |
break | |
case 2: | |
b.setBackgroundImage(UIImage(named: "star2"), forState: .Highlighted) | |
break | |
case 3: | |
b.setBackgroundImage(UIImage(named: "star3"), forState: .Highlighted) | |
break | |
case 4: | |
b.setBackgroundImage(UIImage(named: "star4"), forState: .Highlighted) | |
break | |
case 5: | |
b.setBackgroundImage(UIImage(named: "star5"), forState: .Highlighted) | |
break | |
default: | |
break | |
} | |
} | |
} | |
func starTitle() -> String { | |
guard self.starRating > 0.0 else { | |
return "Transaction Rating" | |
} | |
let title = [String](count: Int(self.starRating), repeatedValue: "✭") | |
return title.joinWithSeparator("") | |
} | |
//MARK: Action Methods | |
@IBAction func highlightButtonsUpto(button:UIButton) { | |
let targetValue = (button.tag) | |
let _ = starCollection.map({ $0.highlighted = false }) | |
for b in starCollection { | |
if targetValue > b.tag { | |
b.highlighted = true | |
} | |
} | |
//keeps last button highlighted | |
button.cancelTrackingWithEvent(nil) | |
button.highlighted = true | |
starRating = Float(targetValue) | |
ratingDelegate?.ratingWasChanged(Float(targetValue)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment