-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRatingControl.swift
More file actions
81 lines (62 loc) · 2.39 KB
/
RatingControl.swift
File metadata and controls
81 lines (62 loc) · 2.39 KB
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
//
// RatingControl.swift
// RowTime
//
// Created by Paul Ventisei on 03/05/2016.
// Copyright © 2016 Paul Ventisei. All rights reserved.
//
import UIKit
class RatingControl: UIView {
// MARK: Properties
var rating = 0 {
didSet {
setNeedsLayout()
}
}
var ratingButtons = [UIButton]()
var spacing = 5
var stars = 5
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let filledStarImage = UIImage(named: "filledStar")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<5 {
let button = UIButton()
button.setImage(emptyStarImage, for: UIControl.State())
button.setImage(filledStarImage, for: .selected)
button.setImage(filledStarImage, for: [.highlighted, .selected])
button.adjustsImageWhenHighlighted = false
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchDown)
ratingButtons += [button]
addSubview(button)
}
}
override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
// Offset each button's origin by the length of the button plus spacing.
for (index, button) in ratingButtons.enumerated() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
override var intrinsicContentSize : CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + spacing) * stars
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Action
@objc func ratingButtonTapped(_ button: UIButton) {
rating = ratingButtons.index(of: button)! + 1
updateButtonSelectionStates()
}
func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerated() {
// If the index of a button is less than the rating, that button should be selected.
button.isSelected = index < rating
}
}
}