以编程方式自动布局各种尺寸的图像数组

时间:2018-03-22 18:35:52

标签: swift uiimageview autolayout swift4 ios-autolayout

我正在制作一个2d益智游戏(网格/棋盘)推箱子,如果有人听说过,下面是代码。我正在寻找一种显示电路板(图像阵列)的方法。

func makeLevel() {
        var cellImageView: [[UIImageView]] = []
        var floorImageView: [[UIImageView]] = []
        let cellWidth = 35
        let cellHeight = 35

        let x0 = 190 - 4 * cellWidth
        let y0 = 300 - 4 * cellHeight

        let imageForCellMarker: [Character: UIImage] = [
            ".": UIImage(named: "poopgoal30x30")!,
            "#": UIImage(named: "wall30x30")!,
            "$": UIImage(named: "box30x30")!,
            "@": UIImage(named: "cat30x30")!,
            "£": UIImage(named: "box30x30")!,
            "&": UIImage(named: "cat30x30")!,
            ]

        //Floor
        for y in 0..<rows {
            floorImageView.append([])
            for x in 0..<cols {
                let image = UIImage(named: "floor30x30")!
                let frame = CGRect(x: x0 + x * cellWidth, y: y0 + y * cellHeight,         width: cellWidth, height: cellHeight)
                let imageView = UIImageView(frame: frame)
                imageView.image = image
                floorImageView[y].append(imageView)
                view.addSubview(imageView)
            }
        }

        //Level
        for y in 0 ..< rows {
            cellImageView.append([])
            for x in 0 ..< cols {
                let image = imageForCellMarker[gameBoard[y][x]]
                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)
            }
        }
    }

由于电路板将在各种行和列中取决于级别,因此我无法将其真正设置为视图中的常量位置。因此,有没有什么样的快速专家会告诉我如何自动布局网格,以便它适合所有设备?

1 个答案:

答案 0 :(得分:0)

我建议使用自动布局和约束,而不是绝对值......这样可以避免手动计算尺寸和位置。

要让您的当前代码居中“游戏区域”,您可以更改这两行:

  <div *ngIf=" type === 'HTC' " class="form-group">

to(我假设上面 let x0 = 190 - 4 * cellWidth let y0 = 300 - 4 * cellHeight 是行数和列数):

4

因此...

    let x0 = Int(view.frame.size.width) / 2 - cols * cellWidth / 2
    let y0 = Int(view.frame.size.height) / 2 - rows * cellHeight / 2

让游戏区域在视图中居中,将起始X设置为中心X - 游戏区域宽度的一半,并将起始Y设置为中心Y - 高度的一半游戏区。

这将使您的游戏区域居中,无论设备如何。但是,对于较大的设备,它将是整个视图中心的一个小区域...因此您需要根据屏幕/视图的大小计算cols * cellWidth // equals the full width of the game area rows * cellHeight // equals the full height of the game area cols * cellWidth / 2 // equals one-half the width of the game area rows * cellHeight / 2 // equals one-half the height of the game area Int(view.frame.size.width) / 2 // equals the horizontal center of the view Int(view.frame.size.height) / 2 // equals the vertical center of the view cellWidth