So I have setup a UIView that contains a UIScrollView (and child content view) that has sub views that are series of UILabels and UIViews that grow and shrink depending on the content contained in them, all using AutoLayout from the Storyboard. This works when I have something like Label - Label - Label - View w/o any issues, however if I put an empty UIView in-between two labels and insert sub views on the UIView, I'm not seeing the results I'm expecting. I have the following layout in a storyboard:
...where the teal and blue views are labels that grow to infinite height and the orange view (optionsPanel) is an empty UIVIew that I later inject sub views into. The rest of the stuff on the window is UILabels and UISegment controls. Between each row of views I have a Vertical Space constraint with a constant of 8. This all worked beautifully until I had to put in the empty UIView and programmatically inject sub views. The code I would expect to work would be something like (optionsPanel is the orange colored UIView)...
optionsPanel.translatesAutoresizingMaskIntoConstraints = YES;
NSArray *options = [product objectForKey:#"options"];
lastTop = 10;
for(int i=0;i<options.count; i++) {
NSDictionary *option = [options objectAtIndex:i];
NSArray *values = [option objectForKey:#"values"];
if([self hasNoneValue:values] && values.count == 2) {
NSDictionary *value = [self notNoneValue:values];
M13Checkbox *optionCheck = [[M13Checkbox alloc] initWithTitle:[option objectForKey:#"name"]];
optionCheck.frame = CGRectMake(0, lastTop, 280, 25);
[optionsPanel addSubview:optionCheck];
lastTop += 25;
} else {}
}
...where the orange UIView would magically grow and everything would just get pushed around accordingly, however this is what I'm seeing:
...the orange UIView does not grow at all, and the other two top UIView have gone somewhere off the screen. So my next guess was to turn off the Autoresizing Mask using...
optionsPanel.translatesAutoresizingMaskIntoConstraints = NO;
...but I'm getting a result where everything appears to be working but the orange UIView (optionsPanel) has no height for whatever reason and looks like:
This is getting closer to what I would expect, so I thought I would force the height of the orange UIView using code like...
frame = optionsPanel.frame;
frame.size.height = lastTop;
optionsPanel.frame = frame;
...but this appears to have no affect on anything.
Purely guessing, I found that this code almost works, if I arbitrary set the optionPanel's origin to something much larger than the space that is needed....
optionsPanel.translatesAutoresizingMaskIntoConstraints = YES;
NSArray *options = [product objectForKey:#"options"];
lastTop = 10;
for(int i=0;i<options.count; i++) {
NSDictionary *option = [options objectAtIndex:i];
NSArray *values = [option objectForKey:#"values"];
if([self hasNoneValue:values] && values.count == 2) {
NSDictionary *value = [self notNoneValue:values];
M13Checkbox *optionCheck = [[M13Checkbox alloc] initWithTitle:[option objectForKey:#"name"]];
optionCheck.frame = CGRectMake(0, lastTop, 280, 25);
[optionsPanel addSubview:optionCheck];
lastTop += 25;
} else {}
}
lastTop += 10;
frame = optionsPanel.frame;
frame.size.height = lastTop;
frame.origin.y += 300; //some arbitrarily large number
optionsPanel.frame = frame;
..which gives this result:
...but apparently the AutoLayout has decided that the name label needs to take up the extra space. Its an ugly approach but if I could figure out how much space I need then I could just push everything down, if I had to. What's the secret to having a dynamic UIView between two dynamically sized labels and everything just work???
As #Timothy says, you need to manually add constraints to the subviews of the orange view if you want it to resize based on its contents—views don’t do this by default.
In general, if you’re using autolayout in a window, you should never be manually setting the frame of any view. Autolayout overrides any frames you set the every time it’s called, so even if you manage to manually get it working for a second it’ll fail the next time anything triggers a layout.
For views created in code, it's perfectly fine to set their frames as long as their translatesAutoresizingMaskIntoConstraints property is YES (the default, by the way).
However, for a view instantiated in storyboard or a nib, you can not set its translatesAutoresizingMaskIntoConstraints to YES.
Related
I'm running into issues with my UI when adding a dynamic number of child UIView elements into a "container" UIView. Basically I need to be able to dynamically resize the container view (self.containerAView below) to fit the height of all the "children" subViews that have been added to it. All the attempts that I have done thus far to reset the frame haven't worked. It is worth noting that the initial size is defined in the *.xib file that is initially loading the containerAView (UIView) element with an initial size of 300x200 (w x h).
- (void)drawScreen {
// handle all screen presentation initialization here
// programatically create a dynamic number of child views to add to the container view
for (int i = 0; i < 3; i++) {
int childViewHeight = 60;
int childViewWidth = 300;
UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, (i * childViewHeight) + (i * 10), childViewWidth, childViewHeight)];
childView.backgroundColor = [UIColor blackColor];
[self.containerAView addSubview:childView];
}
// build a mapping dictionary for all child elements in the container view
NSMutableDictionary *containerASubViewDictionary = [[NSMutableDictionary alloc] init];
for (int i = 0; i < [self.containerAView.subviews count]; i++) {
[containerASubViewDictionary setValue:self.containerAView.subviews[i] forKey:[NSString stringWithFormat:#"childView%d", i]];
}
// WHAT TO ADD HERE TO HANDLE RESIZING self.containerAView height???
}
Any sort of help on dynamically resizing the container view would be greatly appreciated as I have been unable to find any solution as of yet.
One way, which is probably the most up to date approach, would be to add 4 auto layout constraints to the containerview in interface builder.
Add the four constraints: x = 0, y = 0, width = 300 & height = 200
Now click on the width constraint in interface builder to highlight it and then control drag it into your .h file and give it a name, like containerWidth.
#property (strong, nonatomic) IBOutlet NSLayoutConstraint *containerWidth;
Repeat with the height.
In your .m file you can adjust the height and width in your drawScreen method by manipulating the contstraints.
self.containerWidth.constant = width; // your calculated new width
self.containerHeight.constant = height; // your calculated new height
You seem to be attempting to change the height of your container's frame. A frame has an origin and a size. Try manipulating these properties:
self.containerView.frame.origin.x
self.containerView.frame.origin.y
self.containerView.frame.size.height
self.containerView.frame.size.width
I'm developing an app for iPhone and I have a strange problem. I tried to solve this by myself but after 3 days I didn't found a solution anyway.
I have a scrollview in which I dynamically create other views and subviews, this is the code:
for (int i=0; i<dim; i++) {
UITextView *posted_nick= [[UITextView alloc] initWithFrame:CGRectMake(paddWidth, heightUpdateImageScrollview+paddHeight/2, screenWidth-2*paddWidth, 37)];
//textview customization...
[imagesScrollView addSubview:posted_nick];
row_images_like = [[UIView alloc] initWithFrame:CGRectMake(paddWidth,heightUpdateImageScrollview+paddHeight+37+heightImageInScrollView,screenWidth-2*paddWidth,80)];
//set the tag = id
row_images_like.tag = [id_image intValue];
UIImageView *like_mini = [[UIImageView alloc] initWithFrame:CGRectMake(0,15,25,25)];
//imageview customization...
//tag = id+1..
NSInteger x = [id_image intValue] + 1;
number_like.tag = x;
[row_images_like addSubview:like_mini];
UITextView *number_like = [[UITextView alloc] initWithFrame:CGRectMake(paddWidth*5/2,10,55,37)];
//textview customization...
//tag = id+2..
NSInteger x = [id_image intValue] + 2;
number_like.tag = x;
[row_images_like addSubview:number_like];
[imagesScrollView addSubview:row_images_like];
}
Now, all works great and when I click on the image view "like_mini", I can find the other views in the same row with the appropriate tag
(UIView *thisView = (UIView*)[imagesScrollView viewWithTag:ID_IMAGE];)
The problem is where I update my scrollview. When the user scrolls to the top, if there are new images to show, I call the same function that creates the views, and all the other views (that already exist) are moved some down. Why, when I try to find a view by tag in my scrollview, all works at the first time, but don't work for the new images created with the same code?
If i remove all the views in the scrollview, before adding the new views, it works. But i don't want to remove the oldest view.
When it works, I have in my console the view (row_images_like) with tag.
When it doesn't work, I receive a _UITextContainerView. What is this?
Hope I explained myself.
Hi there the only reason the images moves down is because you are not assigning the proper tags, please give appropriate value of tag to uiview, uiimageview and uitextview.
row_images_like.tag = [id_image intValue] + 1000;
For fetching the view get it done similarly what you did before only add thousand to it.
UIView *thisView = (UIView*)[imagesScrollView viewWithTag:ID_IMAGE+1000];
Also one error :
number_like.tag = x;
How does the above line object i.e "Number_like" comes before initialising it and change the tag value of other objects to "+2000" and "+3000"
Try removing all views added to scrollview, before loading scrollview again
Write this line above for loop
for (UIView *v in [imagesScrollView subviews])
{
[v removeFromSuperview];
v = nil;
}
I'm programming an app for iOS 7 in Xcode 5.
I have three text boxes at the top of my page, each right above the other. Let's call them topTextBox, middleTextBox, and bottomTextBox.
My intent is that depending on a particular condition, the topTextBox might not be visible (or present, really) when the view loads.
If topTextBox isn't present (or hidden, or whatever) I would like middleTextBox and bottomTextBox to be placed further up the page...as if topTextBox wasn't ever there in the first place (so middleTextBox is in the spot topTextBox used to be in, and bottomTextBox is in the spot middleTextBox was in).
I'm using storyboards with AutoLayout ON. I can't seem to figure out what to do with the constraints for each of the three textBoxes to make this work. Making middleTextBox and bottomTextBox sit higher on the page when topTextBox is hidden doesn't need to be dynamic--I make the decision to show or not show topTextBox in ViewDidLoad()--I just need to get them to show up in the right place depending on my conditions.
Questions:
a. Is making topTextBox.hidden = YES the right way to get topTextBox to not be shown? Or is there some way to make it not noticed by the view at all?
b. What do I do with these constraints on middleTextBox and bottomTextBox to move them up on the page in this condition?
c. Is there anything else I should know to get this to work that I'm not thinking of? Perhaps a better method?
Thanks.
Have you tried just hard coding the frame logic? This could be very effective. All you have to do is conditionally populate an array containing pointers to your text fields and then perform a little frame arithmetic on their y origins. For example, this could easily display all the fields:
NSArray *fields = #[topTextField, middleTextField, bottomTextField];
for (int i = 0 ; i < fields.count ; i ++) {
UITextField *field = fields[i];
[field setFrame:CGRectMake(20.0, 20.0 + (i * 50.0), 280.0, 34.0)];
}
Produces this:
Or at its most basic level, something like this could be used to check whether any of the text fields should/shouldn't be shown, and either hides them, or adjusts their frame accordingly.
BOOL shouldShowTop = YES;
BOOL shouldShowMiddle = NO;
BOOL shouldShowBottom = YES;
NSMutableArray *fields = [NSMutableArray new];
if (shouldShowTop) {
[fields addObject:topTextField];
}else{
[topTextField setHidden:YES];
}
if (shouldShowMiddle) {
[fields addObject:middleTextField];
}else{
[middleTextField setHidden:YES];
}
if (shouldShowBottom) {
[fields addObject:bottomTextField];
}else{
[bottomTextField setHidden:YES];
}
for (int i = 0 ; i < fields.count ; i ++) {
UITextField *field = fields[i];
[field setFrame:CGRectMake(20.0, 20.0 + (i * 50.0), 280.0, 34.0)];
}
Will produce this:
Setting the height constraint of topTextField to 0 will help you to achieve this.
provided all textfields are connected through vertical space constraint
Setting the height of topTextField so that it has zero height could also work for you.
CGRect frame = topTextField.frame;
frame.size.height =0;
topTextField.frame = frame;
This is a good choice should you want to animate its re-appearance later on.
As for constraints, constrain the top of the topTextField to the superview, and then the top of middleTextField and bottomTextField to the bottom of the textfield above.
Do not set a constraint for the height of topTextField, but do set width constraints. You'll need to set the height of topTextField in viewDidLoad:
My original question is posted here, but I wanted to open new question to explain in better in briefly way about my issue.
I try to draw 3 subviews on a scrollview and make that scroll horizontally. The content size is Ok, I can scroll up to three times (width of 3 subviews) but the problem is that all of the subviews are drawn over each other so obviously I can see only the last subview.
The subview is loaded from a xib file. Here is the relevant code:
startX = 0;//static int startX ;
for (App_Table *_appTable in sorted) {
NSArray *arr = [[NSBundle mainBundle] loadNibNamed:#"AppTableView" owner:self options:nil];
AppTableView *aView = [arr objectAtIndex:0];
aView.frame = CGRectMake(startX, 0, aView.bounds.size.width, aView.bounds.size.height);
aView.backgroundColor = [UIColor redColor];
[self.scrollView addSubview:aView];
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width+aView.frame.size.width
,self.scrollView.contentSize.height);
startX = startX + aView.frame.size.width;
AppTableView *_appTableView = (AppTableView *) [[self.scrollView subviews] lastObject];
_appTableView.txtADDRESS.text = _appTable.address;//Fill in the form, no need to write all the form fields code because it's the same way.
}
As you can see, the X origin is incremented by the width of the view, I debugged to confirm, however the subviews are overlapping one above the other, and finally just one subview (the last one) is visible. I checked that by setting the background to red color, and only one red background subview is loaded.
If you can help with and want to post your answer in the original question for which I make a bounty, feel free.
Thanx.
I am getting strange behavior with UIScrollView subviews, the idea is to create programmatically an instance of UIView with a customized nib file which is a form in my case, fill that form with data from a model class, and add it as subview for my UIScrollView. The problem is when I deal with more than one subview, the UIScrollView only keep the latest subview, so if I created three subviews, the scrollview will show only the third (the latest) subview. Although the page control is set to the coreect number of subviews (three).
The project is too long, so I will try to explain brievely my issue with the relevant code:
- (void)viewDidLoad {
NSArray *sorted = [appArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];//this array contains the data from model, I debugged that to make sure I got the exact data, no more no less :)
//Loop all NSManaged objects, for example let's say I have 3 model objects, don't worry about how I get data etc, because I debugged all and maked sure all data objects number are exact, etc.
for (App_Table *_appTable in sorted) {
//This looped 3 times as expected, I debugged that also and maked sure on each iteration I got the data I expected to have
//App_Table is a subclass of NSManagedObject, it's my model class and get its data from coredata file
[self addMoreView];//Call this method will create a new subview and add it as subview to the UIScrollView, it will also update the page control, update the content size property, etc.
AppTableView *_appTableView = (AppTableView *) [[self.scrollView subviews] lastObject];//Remember addMoreView method create a new instance of AppTableView and add it as subview for the UIScrollView property, then I get that subview to fill it with data here
_appTableView.txtADDRESS.text = _appTable.address;//Fill in the form, no need to write all the form fields code because it's the same way.
// Scroll To First Page...
self.pageControl.currentPage = 0;
[self.scrollView scrollRectToVisible:CGRectMake(0, 0, viewWidth, viewHeight) animated:YES];
self.scrollView.contentSize = CGSizeMake(viewWidth*noOfItems, viewHeight);//Set the content size to the sum of subviews width, I also debugged that to check it's correct
self.scrollView.delegate = self;
[super viewDidLoad];
}
Ok, so when I have three subviews, the scrollview will load with the width of three subviews as calculated with the line above:
self.scrollView.contentSize = CGSizeMake(viewWidth*noOfItems, viewHeight);//Set the content size to the sum of subviews width, I also debugged that to check it's correct
And I can scroll till 3 moves (which is the number of subviews) and the UIPageControl is also set to three dots, but only ONE subview is visible, only the latest one I can see, the two other subviews disappeared, the scroll view calculated content size for them but they are not visible. Any thoughts ? Thanx.
EDIT:
It's worth to note that the first time I edit the view, all goes fine, when I deal with 3 subviews, they are all visible, but when I go to another view and get back to this view, only the last subview is visible.
Also, I am working on an iPad project for that with a split view.
EDIT:
This is the code of the method which draw new subview for the UIScrollView
-(IBAction) addMoreView
{
NSArray *arr = [[NSBundle mainBundle] loadNibNamed:#"AppTableView" owner:self options:nil];
AppTableView *aView = [arr objectAtIndex:0];
[aView setFrame:CGRectMake(startX, 0, aView.bounds.size.width, aView.bounds.size.height)];
[self.scrollView addSubview:aView];
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width+aView.frame.size.width
, self.scrollView.contentSize.height);
startX = startX + aView.frame.size.width;//Update the X position, first 0, then 600, 1200, and so on.
[self.scrollView scrollRectToVisible:aView.frame animated:YES];
NSLog(#"%f",self.scrollView.contentSize.width);
NSLog(#"%f",self.scrollView.contentSize.height);
}
Suppose I have 3 subviews, the method above will be called 3 times since it's put inside the for loop. So here is the result of NSLogs for the above method:
NSLog(#"%f",self.scrollView.contentSize.width);
NSLog(#"%f",self.scrollView.contentSize.height);
First iteration:
600.000000
0.000000
Second iteration:
1200.000000
0.000000
Third iteration:
1800.000000
0.000000
EDIT:
The command suggested by rob mayoff allows me to see why this happen:
| | | | <AppTableView: 0x1eef4700; frame = (0 18; 600 430); autoresize = LM+RM+TM+BM; tag = 990; layer = <CALayer: 0x1eef4790>>
| | | | <AppTableView: 0x1ee3f380; frame = (0 18; 600 430); autoresize = LM+RM+TM+BM; tag = 991; layer = <CALayer: 0x1ee3f410>>
| | | | <AppTableView: 0x1ee56910; frame = (0 18; 600 430); autoresize = LM+RM+TM+BM; tag = 992; layer = <CALayer: 0x1ee3f410>>
All Three subviews are drawn in the same frame, so they are above each other, but when I debug that with breakpoints in runtime, the x is changing, first time 0, then 600 then 1200 which make me think it's drawing correctly. How to fix that especially that the x value is being incremented correctly, so what's the problem and why they still drawing on the same x coordinate?
First things first, you should place the [super viewDidLoad] call at the top of your - (void)viewDidLoad method, not at the bottom.
Given that it's not clear enough what you are actually seeing and what you expect to see, providing a minimum working example of your problem as a downloadable project would help us to help you. If you just try to reproduce this in a separate view controller that does not interact with managed objects, but uses some statically provided data, others will be able to reproduce it themselves and debug it. Or you might just as well figure it out yourself in the process.
I am getting back a bit late, but finally I figure out the fix for my problem so thought it's good to share it to save someone else's time.
For my case, the scrollview is a custom view in a nib file. So by activating its Autosizing masks left and top, the bug was fixed.
This block of code in -addMoreView is the problem:
AppTableView *aView = [arr objectAtIndex:0];
[aView setFrame:CGRectMake(startX, 0, aView.bounds.size.width, aView.bounds.size.height)];
[self.scrollView addSubview:aView];
If startX never changes, you're adding all of these views at the same spot.
Surely your not setting the content size correctly for 3 items:
self.scrollView.contentSize.width+aView.frame.size.width
should be
self.scrollView.contentSize.width+ ( aView.frame.size.width * NUMBER_OF_SUBVIEWS)
I presume when you scroll horizontally on the scrollview, the content size only allows enough room for one subview correct ?
used a static variable which is reinitialized to 0 on load, then it gets incremented by the width of the subview to start drawing on new X position.
Try to set the autoresizingMask of aView to UIViewAutoresizingNone inside the addMoreView method.
I created a project that uses your code in the sister post, and its working just fine. I added several tests on the autoresizing masks as you can see below. I suggest you compare it to what you are doing. Weird things happen when the masks on EITHER the subviews or the scrollView are not set to being tied to the top/left.
My modified code:
NSArray *colors = #[ [UIColor redColor], [UIColor greenColor], [UIColor blueColor] ];
UIViewAutoresizing mask;
mask = [self.scrollView autoresizingMask];
//assert(!self.scrollView.autoresizesSubviews); // has no affect here
if((mask & (UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin)) != mask) NSLog(#"scrollView MASK WRONG");
for (int i=0; i<3; ++i) {
NSArray *arr = [[NSBundle mainBundle] loadNibNamed:#"AppTableView" owner:self options:nil];
NSLog(#"scrollView frame: %#", NSStringFromCGRect(self.scrollView.frame));
if((mask & (UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin)) != mask) NSLog(#"aView MASK WRONG");
AppTableView *aView = [arr objectAtIndex:0];
assert([aView isKindOfClass:[AppTableView class]]);
NSLog(#"orig aView frame: %#", NSStringFromCGRect(aView.frame));
UIViewAutoresizing mask = [aView autoresizingMask];
if((mask & (UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin)) != mask) NSLog(#"aView MASK WRONG");
aView.frame = CGRectMake(startX, 0, aView.bounds.size.width, aView.bounds.size.height);
NSLog(#"changed aView frame: %#", NSStringFromCGRect(aView.frame));
aView.backgroundColor = colors[i];
[self.scrollView addSubview:aView];
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width+aView.frame.size.width
,self.scrollView.contentSize.height);
startX = startX + aView.frame.size.width;
//AppTableView *_appTableView = (AppTableView *) [[self.scrollView subviews] lastObject];
//_appTableView.txtADDRESS.text = _appTable.address;//Fill in the form, no need to write all the form fields code because it's the same way.
}
NSLog(#"scrollView frame: %#", NSStringFromCGRect(self.scrollView.frame));
NSLog(#"scrollView contentOffset: %#", NSStringFromCGPoint(self.scrollView.contentOffset));