Vamos Vamos - 5 months ago 13
Swift Question

Unable to see subview inside UIScrollView through programatically constraints

I'm trying to add UIView inside UIScrollView using programatically constraints but i think due to constraints missing I'm unable to see UIView. When i tried to add by CGRectMake its working fine also i checked with below code, in view hierarchy there is view inside UIScrollview.

I tried no. of solutions but didn't get any success

UIScrollView with iOS Auto Layout Constraints: Wrong size for subviews

Programmatically creating controller with UIScrollView and AutoLayout is not sizing the views properly

Here is my code

vendorDetailsScrollView = UIScrollView()
vendorDetailsScrollView!.translatesAutoresizingMaskIntoConstraints = false
vendorDetailsScrollView!.backgroundColor = UIColor.redColor()
self.view.addSubview(vendorDetailsScrollView!)

vendorSubView = UIView()
vendorSubView!.translatesAutoresizingMaskIntoConstraints = false
vendorSubView!.backgroundColor = UIColor.greenColor()
self.vendorDetailsScrollView!.addSubview(vendorSubView!)

viewDictionary!["vendorDetailsScrollView"] = vendorDetailsScrollView!
viewDictionary!["vendorSubView"] = vendorSubView!

metricDictionary!["navigationHeight"] = navigationHeight
metricDictionary!["vendorDetailsScrollViewHeight"] = self.view.frame.size.height - navigationHeight
metricDictionary!["vendorSubViewHeight"] = 100

self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[vendorDetailsScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricDictionary!, views: viewDictionary!))

self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-navigationHeight-[vendorDetailsScrollView(vendorDetailsScrollViewHeight)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricDictionary!, views: viewDictionary!))

self.vendorDetailsScrollView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[vendorSubView]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricDictionary!, views: viewDictionary!))

self.vendorDetailsScrollView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[vendorSubView(vendorSubViewHeight)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricDictionary!, views: viewDictionary!))

Answer

You need to add the following code

self.vendorDetailsScrollView.addConstraint(NSLayoutConstraint(item: vendorSubView, attribute: .Width, relatedBy: .Equal, toItem: vendorDetailsScrollView, attribute: .Width, multiplier: 1.0, constant: 0))

instead of

self.vendorDetailsScrollView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[vendorSubView]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricDictionary!, views: viewDictionary!))
Comments