ios - 如何在 Swift 3 中显示矩阵
问题描述
我有一个值为 1 或 0 的整数矩阵。我想在视图上显示一个元素,用于矩阵中值为 1 的位置使用UIImage
视图。我在 Xcode 8 和 Swift 3 中工作。我用 HTML(使用单选按钮)做到了这一点,但在 Swift 中我真的不知道。
我想要这样的东西:
解决方案
您可以像这样存储数据:
let data: [Int: [Int]]
然后您可以对其进行迭代,检查它们是 0 还是 1,并根据结果构建视图,如下所示:
- 创建 1 个水平堆栈视图
- 创建与列数相等的垂直堆栈视图数
- 在枚举数据时,对于每个垂直堆栈视图,如果 data == 0 则添加一个空视图,如果 data == 1 则添加一个具有固定大小的图像视图
- 当一个“列”准备好时,将其添加到水平堆栈视图
- 在屏幕上显示水平堆栈视图
如果你稍微玩一下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)
}
}
推荐阅读
- python - 根据特定条件将熊猫中的 2 个字符串列组合成一个新列的最佳方法是什么?
- ios - addTarget 不适用于 UICollectionViewCell 中的按钮
- c# - 在 Xaml (UWP) 中格式化 TimeSpan
- python - 通过 Google Sheets API 和 Python 阅读 Sheet2
- ada - 更改构建目标编译文件的 gps 行为
- python-3.7 - ModuleNotFoundError:没有名为“队列”的模块
- wordpress - 文件权限恢复为 Wordpress 站点的只写
- node.js - 无法使用 DNS 访问服务
- android - Soft Keboard 在片段活动中覆盖 TextInputEditText
- r - 如何在R中按类别对df中的2乘2变量应用包含多元回归的函数?