So I'm trying to clone the Apple weather app. My ViewHierarchy
looks like this:
ViewControllerA
contains a UIScrollView
which in turn contains a UIView
(UIView1)
and the UIView
contains child elements.There is also a button below the UIScrollView
to add more UIView
inside the UIScrollView
. This UIViewController
is designed in IB
using AutoLayout
.
When I click this button ideally I want to clone the UIView1
and add it to the UIScrollView
, to the righthandside end of the currentView
inside the UIScrollView
. This is a horizontal scroll function. This is where I am stuck.
What I have tried are the following: Create a copy of UIView1
in a xib
and load that. Create a UIView
programmatically and load that.
In both the cases I'm facing the auto layout constraints issue. When I load the second view, it's overwritten on top of the existing view. I can hardcode the frame sizes for the cloned UIView
and get it to work but obviously that won't work across devices.
So I'm adding constraints - something like this:
func buildView(startX:CGFloat, model:CityModel) -> UIView {
var frame:CGRect = CGRectMake(0, 0, insideScrollView.bounds.width, insideScrollView.bounds.height)
var cityView:UIView = UIView(frame: frame)
var lFrame:CGRect = CGRectMake(0, 0, 100,50)
var cLabel:UILabel = UILabel(frame: lFrame)
cLabel.text = model.name
cLabel.sizeToFit()
cLabel.textAlignment = .Center
//cityView.addSubview(cLabel)
cityView.layer.backgroundColor = UIColor.blueColor().CGColor
cityView.setTranslatesAutoresizingMaskIntoConstraints(false)
var constX = NSLayoutConstraint(item: cityView, attribute: NSLayoutAttribute.LeftMargin, relatedBy: NSLayoutRelation.Equal, toItem: cityScrollView, attribute: NSLayoutAttribute.LeftMargin, multiplier: 1, constant: 0)
cityView.addConstraint(constX)
return cityView
}
The app crashes unable to load this constraint indicating that the view hierarchy does not support this constraint as all the views are not loaded.
I'll keep digging on how to resolve this but any help will be greatly appreciated. Here's my viewDidLoad
method. Cities is an array of models containing the view data
override func viewDidLoad() {
super.viewDidLoad()
var startScroll = insideScrollView.bounds.width
if cities != nil {
for model in cities.cityModels {
if model.selected {
cityScrollView.addSubview(buildView(startScroll, model: model))
startScroll += cityScrollView.bounds.width
}
}
} else {
var cityModel: CityModel = CityModel(name: "default")
cityModel.selected = false
cities = SearchCityModels.sharedInstance
cities.cityModels.append(cityModel)
}
}
Posting the answer on behalf of @k6sandeep. I had not loaded the view inside the scrollview but was adding constraints to it. So fixed the same by adding constraints after the insideview was loaded.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.