尝试在iPad上绘制一个简单的15x15游戏板。
目前我的代码只在左上角打印一张图片,这似乎可能是添加到imgViewArray但不是100%确定的最终图像。
func createImgBoard() {
let cellWidth = 57
let cellHeight = 57
let squares = 225
var k = 0
var row = 0; var col = 0
let topY = 500-4*cellHeight
let leftX = 384-4*cellWidth
var image: UIImage
for i in 0...14 {
for j in 0...14 {
if board[i][j].symbol == "*" {
image = UIImage(named: "grass57x57px")!
imgViewArray[k].image = image
}
else {
image = UIImage(named: "notgrass57x57px")!
imgViewArray[k].image = image
}
k+=1
print("Added img to imgViewArray " + String(k) + " as " + String(describing: image))
}
}
for i in 0...squares-1 {
imgViewArray[i].frame = CGRect.init(x: leftX+cellWidth*col, y: topY+cellHeight*row, width: cellWidth, height: cellHeight)
self.view.addSubview(imgViewArray[i])
col+=1
if col > 14 {
row+=1
col=0
}
}
}
编辑:由于某种原因,即使代码根本没有改变,它甚至都没有显示单个图像...
答案 0 :(得分:0)
为什么甚至使用两个独立的循环?您可以在第一个(嵌套)循环中完成所需的一切。
class MyViewController: UIViewController {
let board: [[String]] = []
let cellImageView: [[UIImageView]] = []
func createBoardImageViews() {
let cellWidth = 57
let cellHeight = 57
let boardWidth = 15
let boardHeight = 15
let x0 = 384 - 4 * cellWidth
let y0 = 500 - 4 * cellHeight
let imageForCellMarker: [String: UIImage] = [
"*": UIImage(named: "grass")!,
// etc., assuming you have other cell marker types
]
let defaultCellImage = UIImage(named: "notgrass")!
for y in 0 ..< boardHeight {
cellImageView.append([])
for x in 0 ..< boardWidth {
let image = imageForCellMarker[board[y][x]] ?? defaultCellImage
let frame = CGRect(x: x0 + x * cellWidth, y: y0 + y * cellHeight, width: cellWidth, height: cellHeight)
let imageView = UIImageView(frame: frame)
imageView.image = image
cellImageView[y].append(imageView)
view.addSubview(imageView)
}
}
}
}