You can store the data like this:
let data: [Int: [Int]]
Then you can iterate on it, checking if they are 0s or 1s and depending on the result you can build the View something like this:
- Create 1 horizontal stack view
- Create a number of vertical stack views equal to the columns
- While enumerating on the data, for each vertical stack view add an empty view if data == 0 or an image view if data == 1 with a fixed size
- When one "column" is ready add it to the horizontal stack view
- Show the horizontal stack view on the screen
If you play a little with stackviews, it will be an easy task :)
Example code DO REFACTOR!!
class MatrixView: UIView {
private let data: [[Int]]
init(frame: CGRect, data: [[Int]]) {
self.data = data
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
backgroundColor = .yellow
layoutMatrix()
}
private func layoutMatrix() {
let dataLenght = data.count
let dataHeight = data[0].count
let horizontalStackView = UIStackView(frame: bounds)
horizontalStackView.axis = .horizontal
let imageViewWidth = frame.width / CGFloat(dataHeight)
let imageViewHeight = frame.height / CGFloat(dataLenght)
let imageViewRect = CGRect(x: 0, y: 0, width: imageViewWidth, height: imageViewHeight)
for i in 0..<dataLenght {
let verticalStackView = UIStackView()
verticalStackView.axis = .vertical
verticalStackView.widthAnchor.constraint(equalToConstant: imageViewWidth).isActive = true
verticalStackView.heightAnchor.constraint(equalToConstant: frame.height).isActive = true
for j in 0..<dataHeight {
let viewToInsert: UIView
if data[i][j] == 1 {
let image = UIImageView(image: #imageLiteral(resourceName: "icon.png"))
image.widthAnchor.constraint(equalToConstant: imageViewWidth).isActive = true
image.heightAnchor.constraint(equalToConstant: imageViewHeight).isActive = true
viewToInsert = image
} else {
let empty = UIView(frame: imageViewRect)
empty.backgroundColor = .white
empty.widthAnchor.constraint(equalToConstant: imageViewWidth).isActive = true
empty.heightAnchor.constraint(equalToConstant: imageViewHeight).isActive = true
viewToInsert = empty
}
verticalStackView.addArrangedSubview(viewToInsert)
}
horizontalStackView.addArrangedSubview(verticalStackView)
}
addSubview(horizontalStackView)
}
}