首页 > 解决方案 > 如何在 Swift 3 中显示矩阵

问题描述

我有一个值为 1 或 0 的整数矩阵。我想在视图上显示一个元素,用于矩阵中值为 1 的位置使用UIImage视图。我在 Xcode 8 和 Swift 3 中工作。我用 HTML(使用单选按钮)做到了这一点,但在 Swift 中我真的不知道。

我想要这样的东西:

我想如何显示我的矩阵

标签: iosswiftmatrix

解决方案


您可以像这样存储数据:

let data: [Int: [Int]]

然后您可以对其进行迭代,检查它们是 0 还是 1,并根据结果构建视图,如下所示:

  1. 创建 1 个水平堆栈视图
  2. 创建与列数相等的垂直堆栈视图数
  3. 在枚举数据时,对于每个垂直堆栈视图,如果 data == 0 则添加一个空视图,如果 data == 1 则添加一个具有固定大小的图像视图
  4. 当一个“列”准备好时,将其添加到水平堆栈视图
  5. 在屏幕上显示水平堆栈视图

如果你稍微玩一下stackviews,这将是一件容易的事:)

示例代码做重构!

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)
    }
}

推荐阅读