I have a Scroll view in My Viewcontroller. Also I had created a view and connected it to an IBOutlet variable. I need to add many views to the Scroll view.
Code for adding view to ScrollView :
In .h File
UIView *customView_;
@property (nonatomic, retain) IBOutlet UIView *customView;
In .m File :
@synthesize customView = customView_;
for (int i = 0; i < 2; i++) {
UIView *tempView = customView;
tempView.frame = CGRectMake(i * 187, 0, 187, 133);
[scrollView addSubview:tempView];
}
But using the above code, I am only able to see one in the position : 187,0,187,133. If I change the code to for (int i = 0; i < 3; i++) { I am able to see the view only in 374,0,187,133. Can anyone please help me to Resolve this error?
Why is this happening?
Documentation for
addSubview:With this code
You are trying to add the same view twice/three times. With the comment from the documentation, this will remove the previous one, and add it to the new position. (Whilst the superview is the receiver in your case, it still does not mean it’ll copy your view and add it again).
Solution
Unfortunately,
UIViewdoes not follow theNSCopyingprotocol. As such, you can’t create a direct copy of it usingcopy. You will need to create a factory method that will create your view for you, as so:Then call that in your
forloop:This may outgrow your scope of the .xib file. Refer to this answer on how to get this to play nice with Interface Builder.