I'm trying to make a iOS screen displaying a grid, the squares of which can be resized using a slider. currently i am just using a button to test incrementing the square size.
I have hacked some code from here: Swift / UIView / drawrect - how to get drawrect to update when required
My problem is that, although drawrect IS being updated, I would like it to be initialised with each button press. The final response from the above link is beyond my meagre comprehension.
Here is my code:
import UIKit
let screenSize = UIScreen.mainScreen().bounds
var screenWidth = screenSize.width
var screenHeight = screenSize.height*0.9
var squareSize: Int = 10
class ViewController: UIViewController {
// create squares and initialise it with a frame
var squares = SquaresSubclass(frame: CGRectMake(0, 0, screenWidth, screenHeight))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(squares)
}
@IBAction func buttonPressed(sender: AnyObject) {
squareSize = squareSize + 1
squares.setNeedsDisplay()
}
}
class SquaresSubclass: UIView {
// initialise with the frame specified above
override init(frame: CGRect) {
super.init(frame: frame)
}
// no clue - copied from example
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// loop CGRects across and down the screen
override func drawRect(rect: CGRect) {
var xPos = 5
let numberX = Int(0.98*screenWidth)/squareSize
var yPos = 20
let numberY = Int(0.96*screenHeight)/squareSize
for var y = 0; y<numberY ; y++ {
for var x = 0; x<numberX ; x++ {
let color:UIColor = UIColor.yellowColor()
let drect = CGRect(x: CGFloat(xPos), y: CGFloat(yPos), width: CGFloat(squareSize),height: CGFloat(squareSize))
let bpath:UIBezierPath = UIBezierPath(rect: drect)
color.set()
bpath.stroke()
xPos = xPos + squareSize
}
yPos = yPos + squareSize
xPos = 5
}
}
}