How to organize many UIViews in a layout targeting different sized displays
Purpose:
Targeting various iPhone and iPad sized displays that I want to fit in a small square UIView
. Once in place, I want to be able to control each UIView
one so that I can manipulate each one, for example, move and scale each one separately.
One approach is to manually place a small amount UIView
on the Storyboard (Image 1) to be small enough UIView
to fit in the template on the iPad's largest screen, and then wire them all into code. for example
@IBOutlet weak var myView001: UIView!
@IBOutlet weak var myView002: UIView!
...
...
@IBOutlet weak var myView144: UIView!
But the above approach seems very complicated and not elegant.
Question:
How can I dynamically (and elegantly) create many small ones
UIView
that can be patterned to fit the smallest iPhone screen and the largest iPad screen that can be manipulated in Swift code?
Image 1:
source to share
Here's a way to create a subview and add it to the current view:
let subview = UIView()
subview.backgroundColor = .black
subview.frame = CGRect(x: 10, y: 10, width: 30, height: 30)
self.view.addSubview(subview)
Another way to initiate multiple subzones, for example 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)
}
You need to identify the frame, calculate the distance and size of the views, and add them to the current view.
source to share