Wayne Filkins Wayne Filkins - 6 months ago 13
Swift Question

populate view with small squares

Okay this one really made my head hurt but I'm sure someone smarter than me can figure this out easily. I have some variables which calculate how many small squares can fit in a view. I want to programmatically populate this view with small squares in a specific order. I want to animate this and change colors and all this other stuff but the part I am really struggling with is getting these squares in the right order. I will try to illustrate the order I'm trying to add these views. I hope this comes out okay.




| 1 | 3 | 6 | 11 | 18 |



| 4 | 2 | 8 | 13 | 20 |



| 7 | 9 | 5 | 15 | 22 |



|12|14|16| 10 | 24 |



|19|21|23| 25 | 17 |



or another cool way would be:




| 1 | 3 | 8 | 15 | 24 |



| 4 | 2 | 6 | 13 | 22 |



| 9 | 7 | 5 | 11 | 20 |



|16|14|12| 10 | 18 |



|25|23|21| 19 | 17 |



Okay so incase you don't see the pattern, it starts at the top left. It moves over 1 and down 1, then populates the cells above that and to the left of it, starting at the outer top and left, and moving inward.

This is the code I have so far:

let numberOfColumns: CGFloat = 10
let w = self.view.frame.width
let h = self.view.frame.height
let squareSideLength = w / numberOfColumns
let numberOfRows = h / squareSideLength
let area = numberOfColumns * numberOfRows
let areaInt = Int(ceil(area))


for i in 1...areaInt {
self.square.frame = CGRect(x: , y: , width: squareSideLength, height: squareSideLength)
self.view.addSubview(square)
}


I'm not sure how to do the "for" loop or loop(s) to populate it in this crazy order. I really hope someone can figure this out!

Answer

Try this! This is a complete viewController (example) that:

  • Creates a maxtrix of numbers
  • Animates the color change of the cell in order of number

Hopefully this gets you closer to what you wanted!

import UIKit

class viewController: UIViewController {

  let numberOfRows = 10                   //numberOfRows and columns to you can change as needed
  let numberOfColumns = 10
  var currentNumber = 1                   //set the first value in the table, can start anywhere
  typealias Position = (Int, Int)
  var currentPostion = (0,0)              //start at 0,0 in the grid
  var rows = [[Int?]]()                   //rows will hold an array of columns (which is also an array)

  var boxes = [UIView]()
  var boxTracker = 0
  var timer = NSTimer()

  override func viewDidLoad() {
    super.viewDidLoad()

    populateMatrix()                     //create the row/column matrix


    timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: #selector(self.timerTicked), userInfo: nil, repeats: true)

  }

  func timerTicked() {
    UIView.animateWithDuration(1.0) {
      self.boxes[self.boxTracker].backgroundColor = UIColor.yellowColor()
    }
    boxTracker += 1
    if boxTracker >= boxes.count {
      timer.invalidate()
    }
  }

  func populateMatrix() {
    rows = createEmptyMatrix()
    while currentPostion < (numberOfRows, numberOfColumns) {
      if valueAtPosition(currentPostion) == nil {         //check the current position
        setValueAtPosition(currentPostion, value: currentNumber)  //if it's nil, assign it the next number and increment it
        currentNumber += 1
      }
      let positionNumber = currentPostion.0
      for pos in (0..<positionNumber).reverse() {   //look up from the current postion and fill it in if it's nil
        let upPosition = (pos, currentPostion.1)
        if valueAtPosition(upPosition) == nil {
          setValueAtPosition(upPosition, value: currentNumber)
          currentNumber += 1
        }
        let leftPosition = (currentPostion.1, pos)   //look left from the current position and fill it in if it's nil
        if valueAtPosition(leftPosition) == nil {
          setValueAtPosition(leftPosition, value: currentNumber)
          currentNumber += 1
        }
      }
      currentPostion = (currentPostion.0 + 1, currentPostion.1 + 1)   //move diagonally 1 postion and start over again!
    }
  }

  func createEmptyMatrix() -> [[Int?]] {
    var viewMatrix = [[Int?]]()
    for _ in 0..<numberOfRows {
      let newColumn = [Int?](count:numberOfColumns, repeatedValue: nil)    //create a column array of nil values and add them to rows
      viewMatrix.append(newColumn)
    }
    return viewMatrix
  }

  func valueAtPosition(position: Position) -> Int? {
    return rows[position.0][position.1]
  }

  func setValueAtPosition(position: Position, value: Int) {
    rows[position.0][position.1] = value
    drawBoxForPosition(position)
  }

  func drawBoxForPosition(position: Position) {
    let row = CGFloat(position.0)
    let column = CGFloat(position.1)
    let itemWidth = self.view.bounds.width / CGFloat(numberOfColumns)
    let itemHeight = self.view.bounds.height / CGFloat(numberOfRows)

    let frame = CGRectMake(row * itemWidth, column * itemHeight, itemWidth, itemHeight)
    let boxView = UIView(frame: frame)
    boxView.layer.borderColor = UIColor.blackColor().CGColor
    boxView.layer.borderWidth = 0.5
    boxView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(boxView)

    let label = UILabel(frame: boxView.bounds)
    label.text = String(valueAtPosition(position)!)
    label.textAlignment = .Center
    boxView.addSubview(label)

    boxes.append(boxView)
  }
}