目标:
针对不同尺寸的 iPhone 和 iPad 显示器,我想以一种模式排列许多小方形 UIView
。布置到位后,我希望能够控制每个 UIView
,以便我可以操作每个,例如,单独移动和缩放每个。
一种方法是在 Storyboard 上手动放置许多小的 UIView
(图 1),确保有足够小的 UIView
以一种模式排列在最大的 Storyboard 上iPad 屏幕,然后用代码将它们全部连接起来。例如
@IBOutlet weak var myView001: UIView!
@IBOutlet weak var myView002: UIView!
...
...
@IBOutlet weak var myView144: UIView!
但是,上面的方法看起来很复杂,也不优雅。
Question:
How can I dynamically (and elegantly) create many small
UIView
, that can be arranged in a pattern to fit the smallest iPhone screen and the largest iPad screen, that can be manipulated in Swift code?
图 1:
最佳答案
这是一种创建 subview 并将其添加到当前 View 的方法:
let subview = UIView()
subview.backgroundColor = .black
subview.frame = CGRect(x: 10, y: 10, width: 30, height: 30)
self.view.addSubview(subview)
另一种初始化多个 subview 的方法,例如 10:
let subviews = (0 ..< 10).map { _ in UIView() }
for i in 0..<10 {
subviews[i].frame = CGRect(x: 10 * i, y: 10, width: 30, height: 30)
}
您需要识别框架,计算距离和 View 大小,并将它们添加到您当前的 View 中。
关于ios - 如何以针对不同尺寸显示器的模式排列多个 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44904916/