Skip to content

Instantly share code, notes, and snippets.

@fspeirs
Created February 14, 2017 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fspeirs/d64742197a44ac204e82c80a62e3a305 to your computer and use it in GitHub Desktop.
Save fspeirs/d64742197a44ac204e82c80a62e3a305 to your computer and use it in GitHub Desktop.
import UIKit
class ArrayView : UIView {
var data: Array<Int> = []
var views: Array<UIView> = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
self.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
func setData(newData: [Int]) {
data = newData
updateViews()
//setNeedsDisplay()
}
func updateViews() {
// Iterate over data member, setting
if self.views.count != self.data.count {
self.generateViews()
}
else {
for (index, value) in self.data.enumerated() {
self.views[index].frame = rectForBar(ofValue: value, atIndex: index)
}
}
}
func scalingFactor() -> CGFloat {
guard let largestValue = data.max() else {
return 1.0
}
let height = self.frame.size.height
return 1.0 / (CGFloat(largestValue) / (height * 0.95))
}
func scaledBarHeight(value:Int, scalingFactor:CGFloat) -> CGFloat {
return CGFloat(value) * scalingFactor
}
func scaledBarHeight(forValue value: Int) -> CGFloat{
return CGFloat(value) * scalingFactor()
}
func barWidthForBarCount(_ barCount:Int) -> CGFloat {
let width = self.frame.size.width
return width / CGFloat(barCount)
}
func rectForBar(ofValue value: Int, atIndex index: Int) -> CGRect {
let barWidth = barWidthForBarCount(self.data.count)
print(barWidth)
let scalingfactor = scalingFactor()
let xOrigin = CGFloat(index) * barWidth
let barHeight = scaledBarHeight(forValue: value)
let yOrigin = self.frame.size.height - barHeight
return CGRect(x: xOrigin, y: yOrigin, width: barWidth, height: barHeight)
}
func generateViews() {
for (index, value) in self.data.enumerated() {
let rect = rectForBar(ofValue: value, atIndex: index)
let view = UIView(frame: rect)
view.backgroundColor = #colorLiteral(red: 0.968627452850342, green: 0.780392169952393, blue: 0.345098048448563, alpha: 1.0)
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.red.cgColor
addSubview(view)
views.append(view)
}
}
}
func randomArray() -> [Int] {
var a = [Int]()
for i in 0..<10 {
let v = Int(arc4random_uniform(1000))
a.append(v)
}
return a
}
import PlaygroundSupport
let barView = ArrayView()
PlaygroundPage.current.liveView = barView
for _ in 0 ... 20 {
if barView != nil {
barView.setData(newData: randomArray())
}
else {
fatalError("BarView disappeared")
}
RunLoop.current.run(until: Date(timeIntervalSinceNow: 2.0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment