-
Notifications
You must be signed in to change notification settings - Fork 100
/
FloatRatingView.swift
303 lines (245 loc) · 9.48 KB
/
FloatRatingView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//
// FloatRatingView.swift
// Rating Demo
//
// Created by Glen Yi on 2014-09-05.
// Copyright (c) 2014 On The Pursuit. All rights reserved.
//
import UIKit
@objc public protocol FloatRatingViewDelegate {
/// Returns the rating value when touch events end
@objc optional func floatRatingView(_ ratingView: FloatRatingView, didUpdate rating: Double)
/// Returns the rating value as the user pans
@objc optional func floatRatingView(_ ratingView: FloatRatingView, isUpdating rating: Double)
}
/// A simple rating view that can set whole, half or floating point ratings.
@IBDesignable
@objcMembers
open class FloatRatingView: UIView {
// MARK: Properties
open weak var delegate: FloatRatingViewDelegate?
/// Array of empty image views
private var emptyImageViews: [UIImageView] = []
/// Array of full image views
private var fullImageViews: [UIImageView] = []
/// Sets the empty image (e.g. a star outline)
@IBInspectable open var emptyImage: UIImage? {
didSet {
// Update empty image views
for imageView in emptyImageViews {
imageView.image = emptyImage
}
refresh()
}
}
/// Sets the full image that is overlayed on top of the empty image.
/// Should be same size and shape as the empty image.
@IBInspectable open var fullImage: UIImage? {
didSet {
// Update full image views
for imageView in fullImageViews {
imageView.image = fullImage
}
refresh()
}
}
/// Sets the empty and full image view content mode.
open var imageContentMode: UIView.ContentMode = .scaleAspectFit
/// Minimum rating.
@IBInspectable open var minRating: Int = 0 {
didSet {
// Update current rating if needed
if rating < Double(minRating) {
rating = Double(minRating)
refresh()
}
}
}
/// Max rating value.
@IBInspectable open var maxRating: Int = 5 {
didSet {
if maxRating != oldValue {
removeImageViews()
initImageViews()
// Relayout and refresh
setNeedsLayout()
refresh()
}
}
}
/// Minimum image size.
@IBInspectable open var minImageSize = CGSize(width: 5.0, height: 5.0)
/// Set the current rating.
@IBInspectable open var rating: Double = 0 {
didSet {
if rating != oldValue {
refresh()
}
}
}
/// Sets whether or not the rating view can be changed by panning.
@IBInspectable open var editable = true
// MARK: Type
@objc public enum FloatRatingViewType: Int {
/// Integer rating
case wholeRatings
/// Double rating in increments of 0.5
case halfRatings
/// Double rating
case floatRatings
/// Returns true if rating can contain decimal places
func supportsFractions() -> Bool {
return self == .halfRatings || self == .floatRatings
}
}
/// Float rating view type
@IBInspectable open var type: FloatRatingViewType = .wholeRatings
// MARK: Initializations
required override public init(frame: CGRect) {
super.init(frame: frame)
initImageViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initImageViews()
}
// MARK: Helper methods
private func initImageViews() {
guard emptyImageViews.isEmpty && fullImageViews.isEmpty else {
return
}
// Add new image views
for _ in 0..<maxRating {
let emptyImageView = UIImageView()
emptyImageView.contentMode = imageContentMode
emptyImageView.image = emptyImage
emptyImageViews.append(emptyImageView)
addSubview(emptyImageView)
let fullImageView = UIImageView()
fullImageView.contentMode = imageContentMode
fullImageView.image = fullImage
fullImageViews.append(fullImageView)
addSubview(fullImageView)
}
}
private func removeImageViews() {
// Remove old image views
for i in 0..<emptyImageViews.count {
var imageView = emptyImageViews[i]
imageView.removeFromSuperview()
imageView = fullImageViews[i]
imageView.removeFromSuperview()
}
emptyImageViews.removeAll(keepingCapacity: false)
fullImageViews.removeAll(keepingCapacity: false)
}
// Refresh hides or shows full images
private func refresh() {
for i in 0..<fullImageViews.count {
let imageView = fullImageViews[i]
if rating >= Double(i+1) {
imageView.layer.mask = nil
imageView.isHidden = false
} else if rating > Double(i) && rating < Double(i+1) {
// Set mask layer for full image
let maskLayer = CALayer()
maskLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(rating-Double(i))*imageView.frame.size.width, height: imageView.frame.size.height)
maskLayer.backgroundColor = UIColor.black.cgColor
imageView.layer.mask = maskLayer
imageView.isHidden = false
} else {
imageView.layer.mask = nil;
imageView.isHidden = true
}
}
}
// Calculates the ideal ImageView size in a given CGSize
private func sizeForImage(_ image: UIImage, inSize size: CGSize) -> CGSize {
let imageRatio = image.size.width / image.size.height
let viewRatio = size.width / size.height
if imageRatio < viewRatio {
let scale = size.height / image.size.height
let width = scale * image.size.width
return CGSize(width: width, height: size.height)
} else {
let scale = size.width / image.size.width
let height = scale * image.size.height
return CGSize(width: size.width, height: height)
}
}
// Calculates new rating based on touch location in view
private func updateLocation(_ touch: UITouch) {
guard editable else {
return
}
let touchLocation = touch.location(in: self)
var newRating: Double = 0
for i in stride(from: (maxRating-1), through: 0, by: -1) {
let imageView = emptyImageViews[i]
guard touchLocation.x > imageView.frame.origin.x else {
continue
}
// Find touch point in image view
let newLocation = imageView.convert(touchLocation, from: self)
// Find decimal value for float or half rating
if imageView.point(inside: newLocation, with: nil) && (type.supportsFractions()) {
let decimalNum = Double(newLocation.x / imageView.frame.size.width)
newRating = Double(i) + decimalNum
if type == .halfRatings {
newRating = Double(i) + (decimalNum > 0.75 ? 1 : (decimalNum > 0.25 ? 0.5 : 0))
}
} else {
// Whole rating
newRating = Double(i) + 1.0
}
break
}
// Check min rating
rating = newRating < Double(minRating) ? Double(minRating) : newRating
// Update delegate
delegate?.floatRatingView?(self, isUpdating: rating)
}
// MARK: UIView
// Override to calculate ImageView frames
override open func layoutSubviews() {
super.layoutSubviews()
guard let emptyImage = emptyImage else {
return
}
let desiredImageWidth = frame.size.width / CGFloat(emptyImageViews.count)
let maxImageWidth = max(minImageSize.width, desiredImageWidth)
let maxImageHeight = max(minImageSize.height, frame.size.height)
let imageViewSize = sizeForImage(emptyImage, inSize: CGSize(width: maxImageWidth, height: maxImageHeight))
let imageXOffset = (frame.size.width - (imageViewSize.width * CGFloat(emptyImageViews.count))) /
CGFloat((emptyImageViews.count - 1))
for i in 0..<maxRating {
let imageFrame = CGRect(x: i == 0 ? 0 : CGFloat(i)*(imageXOffset+imageViewSize.width), y: 0, width: imageViewSize.width, height: imageViewSize.height)
var imageView = emptyImageViews[i]
imageView.frame = imageFrame
imageView = fullImageViews[i]
imageView.frame = imageFrame
}
refresh()
}
// MARK: Touch events
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Update delegate
delegate?.floatRatingView?(self, didUpdate: rating)
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
// Update delegate
delegate?.floatRatingView?(self, didUpdate: rating)
}
}