A Different Way To Layout Views Programmatically Using Swift

// The different choices of position for the view you're laying out 
enum ViewPosition {
case bottomCentercase bottomLeftcase bottomRightcase topCentercase topLeftcase topRightcase centercase leftcase right}// Usually you want to use the withFrame init unless laying out view with the root view as the guideinit(withFrame ofView: UIView, position: ViewPosition, size:CGSize, padding: (CGFloat,CGFloat)) {self.guide = ofView.frame //1 self.position = position //2self.size = size //3self.padding = padding //4}
// Don't forget to call this at the end of instantiation!func makeInnerLayout() -> CGRect {return CGRect(origin: origin, size: size)}func makeOuterLayout() -> CGRect {return CGRect(origin: outerOrigin, size: size)}
override func viewDidLoad() {super.viewDidLoad()let viewWidth = self.view.bounds.width / 2 - 12//lays out first view inside the root viewlet view1Layout = UIView.ViewLayout(withBounds: self.view, position: .topLeft, size: CGSize(width:viewWidth,height:200), padding: (50,0)).makeInnerLayout()view1 = UIView(frame: view1Layout)view1.backgroundColor = .blackself.view.addSubview(view1)//uses view1 as a guide, is 8 points to the leftlet view2Layout = UIView.ViewLayout(withFrame: view1, position: .right, size: CGSize(width:viewWidth,height:200), padding: (0,8)).makeOuterLayout()view2 = UIView(frame: view2Layout)view2.backgroundColor = .redself.view.addSubview(view2)}
Try to figure out how the code matches with the positions of these views- it will give you insight into the workings of ViewLayout

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam French

Adam French

Systems Social Impact + Web3 Economics + Personal Development & Spirituality. Any questions? Hit me up afrench@designunity.one