I have a view hierarchy like this:
UIView
- ADBannerView
- UIImageView
- UILabel
- UIButton
- UINavigationController
- UIView
I'm loading the image view, label and button from a nib file and the UINavigationController from another nib. All have autoresizing masks set. I'm creating the ADBannerView programmatically.
Now my problem is that I would like the image, label, button to move down and the navigation controller to shrink when I insert an ADBannerView. However this is not happening, instead the ADBannerView is placed on top of the image and the label.
Can anybody explain to me what am I doing wrong here?
In other to get those things to "automatically" shift down when you put in the ADBannerView, you'll need to enclose them in their own view and then change the size and position of that view. Assuming the ADBannerView is 50 pixels tall, you'll want to move that UIView down 50 pixels and reduce its height by 50 pixels.
Assuming that self.enclosingView is the new view that you will use to enclose the image, label and button... and assuming you want to make this animated (you probably do, it usually looks a lot better):
// Start the AdBannerView off of the top of the screen
CGRect adFrame = self.bannerView.frame;
adFrame.origin.x = 0.0;
adFrame.origin.y = 0.0 - adFrame.size.height;
self.bannerView.frame = adFrame;
[UIView beginAnimations:#"Show Ads" context:nil];
// Animate the shrinking of the enclosing view
CGRect enclosingFrame = self.enclosingView.frame;
enclosingFrame.size.height -= self.bannerView.frame.size.height;
enclosingFrame.origin.y += self.bannerView.frame.size.height;
self.enclosingView.frame = enclosingFrame;
// Animate the motion of the bannerView into view
adFrame.origin.y = 0.0;
self.bannerView.frame = adFrame;
[UIView commitAnimations];
Autoresizing mask defines size changes on parent's frame changes, not on sibling insertion/removal. You have to adjust frame for corresponding views programmatically. Kenny Wyland already gave you idea how this can be achieved with less pain. Take a look at CGRectDivide method - with it it's easy to split available space between two views.
Related
I am probably doing something extremely stupid but I cannot figure out why this does not work.
I am trying to perform a simple UIView block animation but have run into trouble. I have recreated in a test project.
I have a view on a View controller, when I press the button, I create a new view and set its frame to be out of the current view (above it). I want to animate the transition so that the view currently on the screen moves downwards out of the view as the new one above it comes down to take its place.
Here is the code which is hooked up to the button,
the original view is hooked up as self.view1
- (IBAction)buttonPressed:(id)sender {
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor blueColor];
float offScreenY = 0 - self.view1.frame.size.height;
CGRect offScreenRect = CGRectMake(0, offScreenY, self.view1.frame.size.width, self.view1.frame.size.height);
view2.frame = offScreenRect;
[self.view addSubview:view2];
float oldY = self.view1.frame.origin.y + self.view1.frame.size.height;
CGRect oldRect = CGRectMake(0, oldY, self.view1.frame.size.width, self.view1.frame.size.height);
[UIView animateWithDuration:0.5 animations:^{
self.view1.frame = oldRect;
view2.frame = CGRectMake(0, 0, self.view1.frame.size.width, self.view1.frame.size.height);
}];
}
This just animates view2 down and does not animate view 1.
If I do not add view 2 as a subview and only put view1's frame change in the animation block then view1 animates correctly.
BUT they will not work together!
Why is this?
This is a classic symptom of having autolayout turned on. If you animate frame, it works, but as soon autolayout reapplies the constraints on the view, view1 will return to its original location. By adding view2, iOS automatically reapplies autolayout constraints immediately and your view1 therefore won't move.
Bottom line, don't use autolayout and try to animate frame properties directly. Two solutions:
The easy solution is to turn off autolayout. Go to IB, select the "File inspector" and uncheck the "Use Autolayout" button:
If you want to keep autolayout on, you shouldn't be animating by changing the frame properties directly. You would animate by change the layout constraint constants. This has been answered elsewhere on S.O., but if you need guidance on that approach, let me know.
The basic idea, though, is to create an IBOutlet for your top constraint for view1 called, say, view1TopConstraint, and then in your animation block you can say
self.view1TopConstraint.constant += self.view1.frame.size.height;
[self.view layoutIfNeeded];
For this to work, though, you'd have to be careful about your other constraints on view1 (e.g., have a height constraint, have no bottom constraint or if you have one, lower its priority, etc.). This can be a hassle the first time you do it, but you'll quickly get the hang of animating by changing constraints.
But, then again, if you're using constraints, you probably shouldn't be defining view2 by its frame, but probably defining constraints for that, too.
In this case it is better for you to have a container view.
Add view1 and view2 inside this container accordingly. Container's some part will be in the screen and container's frame size will be double of the size of a view. Animate the container, so the other two views will be animated accordingly..
My UIScrollView is a ~4500px horizontal view that the user needs to scroll horizontally through to view the content.
I have set it up as follows:
- (void)viewDidLoad
{
[super viewDidLoad];
sview.frame = CGRectMake(0, 0, 568, 320);
sview.contentSize = CGSizeMake(4500, 320);
[sview setScrollEnabled:YES];
}
Yet the scroll view does nothing. Is there something obvious I missed? i've tried literally every tutorial on the web.
I got similar issue. I did following modifications and the scrollView started scrolling for me:
Select to check the 'Bounce Horizontally' property for UIScrollView
in xib.
Move the code following code to viewDidAppear instead of
viewDidLoad:
-(void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
sview.frame = CGRectMake(0, 0, 568, 320);
sview.contentSize = CGSizeMake(4500, 320);
[sview setScrollEnabled:YES];
}
I think this should help you.
I've explained it here, but there are so many answers to this problem that suggests turning off Auto Layout. That fixes the problem but that's not really the correct solution. Here's my answer:
Turning Auto Layout works, but that's not the solution. If you really need Auto Layout, then use it, if you don't need it, turn it off. But that is not the correct fix for this solution.
UIScrollView works differently with other views in Auto Layout. Here is Apple's release note on Auto Layout, I've copied the interesting bit:
Here are some notes regarding Auto Layout support for UIScrollView:
In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. That is, if you pin a view to
the left edge of its superview, you’re really pinning it to the
minimum x-value of the superview’s bounds. Changing the bounds origin
of the superview does not change the position of the view.
The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom,
and right edges within a scroll view now mean the edges of its content
view.
The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the
scroll view. (This should not be confused with the
intrinsicContentSize method used for Auto Layout.) To size the scroll
view’s frame with Auto Layout, constraints must either be explicit
regarding the width and height of the scroll view, or the edges of the
scroll view must be tied to views outside of its subtree.
Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints
between the view and a view outside the scroll view’s subtree, such as
the scroll view’s superview.
Apple then goes on to show example of how to correctly use UIScrollView with Auto Layout.
As a general rule, one of the easiest fix is to create a constraint between the element to the bottom of the UIScrollView. So in the element that you want to be at the bottom of the UIScrollView, create this bottom space constraint:
Once again, if you do not want to use Auto Layout, then turn it off. You can then set the contentSize the usual way. But what you should understand is that this is an intended behaviour of Auto Layout.
First of all you have to add some content to UIScrollSiew as subview for scrolling,without content on UIScrollView how can you scroll?. Here is what i did,just add UIImageView to UIScrollView as subview of size same as size of UIScrollView...
In viewDidLoad method try the following code..
-(void)viewDidLoad
{
UIScrollView *scroll=[[UIScrollView alloc] init];
scroll.frame=CGRectMake(0, 0, 320, 460);
UIImageView *imageView=[[UIImageView alloc] init];
imageView.frame=CGRectMake(0, 0, 320,460);
imageView.image=[UIImage imageNamed:#"chiranjeevi.jpeg"];
scroll.contentSize = CGSizeMake(4500, 460);
[scroll setScrollEnabled:YES];
[scroll addSubview:imageView];
[self.view addSubview:scroll];
}
I tested this code it works well.I hope this code will be helpful to you..
I assume you are adding UISrollingView in your Xib file. This will work for you.
sview.delegate = self;
sview.backgroundColor=[UIColor clearColor];
[sview setCanCancelContentTouches:NO];
sview.indicatorStyle = UIScrollViewIndicatorStyleWhite;
sview.clipsToBounds = YES;
sview.scrollEnabled = YES;
sview.contentSize = CGSizeMake(320,570);
CGPoint topOffset = CGPointMake(0,0);
[sview setContentOffset:topOffset animated:YES];
Also, make sure to give IBOutlet connection in your Xib file.
I also faced the same issue.I added the scroll view in xib.I also added some subviews to this scroll view. The scroll view would stop scrolling after I added the subviews. The solution for this problem was in the xib for the view in file inspector Use Autolayout was checked. I unchecked it and the scroll view scrolled after adding the subviews.
The solution was uncheking the Use Autolayout in file inspector in xib.
I am developing an application in which i am creating small sub views in the same view.
What i want is when i change the value of alpha of the view, the value of alpha for sub view is also getting changed which i do not want.
How to implement the code for changing the value of the view not the small sub views created.
Thanks,
You cannot do that, the alpha is inheritate, so what you have to do is to change the view structure from
YourMainView -> Your SubView
To
ContainerView ->YourMainView
-> Your SubView
So now YourMain View the one that you want to apply the animation, is not the paret view of your current subView, the both views are sibilings, also ContainerView will have a clear background, so it wont affect it will just contain both the views
As suggested already, you should not add YourSubVew as subview of YourMainView.
Make both of your views a subview of an empty and transparent common subview (ContainerView) which has the same size and position that YourMainView currently has.
ContainerView -> YourMainView
-> YourSubView
Make sure to add YourMainView first as subview of ContainerView before you add YourSubView as subview of ContainterView. Otherwise YourMainView may overlap/hide YourSubView.
Doing so you can set both views' alpha independend from each other.
(Omar's answer is quite correct, but his "graphical visualisation" is misleading and it missed the point of the sequence of the subviews.)
Edit:
What you have today is like this:
yourMainView.alpha = 1.0;
...
[yourMainView addSubView:yourSubView];
yourMainView.alpha = 0.1; //probably with animations etc.
What happens is, that yourSubView will "inherit" the alphaValue of its superview.
ANd there is even more to that. Assuming that your subView has an alpha of 0.5, that would effectively become 0.05 when when its superview's alpha is set to 0.1.
Change that code to:
containerView = [[UIView alloc] init]; //you may choose a different init method
//If you use initWithFrame then use the frame of yourMainView.
//However, make sure that ContainterView is of the same size as yourMainView and has the same position.
[containerView addSubView:yourMainView];
yourMainView.alpha = 1.0;
...
[containerView addSubView:yourSubView]; //add it to the container too!
yourMainView.alpha = 0.1; //this will now effect the MainView only.
That is basically all the trick. Views can perfectly well overlap each other without being subviews. Make them subviews only then when they really are subveiws, when they are moved togehter, appear and disappear together, etc.
When is it possible to know the exact size of a UIViewController's view?
The Problem
I have a multi-line UILabel whose frame depends of its text and the width of the parent view. Given that I need to position other views below the UILabel, it's important to make its frame cover exactly the space of the text.
I currently calculate the size like this on viewDidLoad:
labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(self.view.frame.size.width, MAX_HEIGHT)];
The problem is that the width of the parent view changes when the UIViewController is used as a modal form sheet or a popover. If I use autoresizingMask the frame of the UILabel is adjusted accordingly, but it no longer is an exact fit for the text.
Where can I calculate the frame of this UILabel knowing the exact size of the UIViewController's view?
Debugging Efforts
This is the result of printing self.view.frame when showing the UIViewController as a modal form sheet (UIModalPresentationFormSheet).
viewDidLoad: (0.000000;0.000000;320.000000;480.000000)
viewWillAppear: (0.000000;0.000000;768.000000;960.000000)
afterDelay: (0.000000;0.000000;540.000000;576.000000)
The code that produces the above output:
- (void)viewDidLoad {
[super viewDidLoad];
[Utils logFrame:self.view.frame tag:#"viewDidLoad"];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[Utils logFrame:self.view.frame tag:#"viewWillAppear"];
[self performSelector:#selector(afterDelay) withObject:nil afterDelay:0.1];
}
- (void) afterDelay {
[Utils logFrame:self.view.frame tag:#"afterDelay"];
}
That's because your UIViewController's root view is using autoresizingMask. I don't think there is a "perfect timing" to detect the size of your UIViewController's root view unless you override your root view's 'layoutSubviews' method.
If you don't want your view to be automatically resized, just don't use autoresizing and set the size by yourself, it will always be the same size you expected.
If you are not sure what kind of autoresizingMasks your root view is using, NSLog is your friend.
This looks like a bug, the value should be known in viewWillAppear.
The alternative is to subclass your UIView and override layoutSubviews there to arrange the subviews based on content. You'll then have to call [self.view setNeedsLayout] from your view controller every time you update the contents of the label. The system will call it if the view resizes, so that should have you covered.
Try this for finding the label size,
labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(self.label.frame.size.width, MAX_HEIGHT)];
Instead of using the view's width, use the label's width in the constrain size. This should be available in the viewDidLoad, viewDidApper methods of the view controller.
try viewWillAppear. There is no reason for not knowing the size before the the view is about to shown
My app's table view does not occupy the full screen height, as I've allowed 50px at the bottom for a banner.
When I begin typing in the search bar, the search results table view is larger; it fills all available screen space between the search bar and the tab bar. This means that the very last search result is obscured by the banner.
How do I specify the size of the table view used by UISearchDisplayController? There's no bounds or frame property that I can see.
EDIT TO ADD SCREENSHOTS:
This is how the table view is set up in IB. It ends 50px short of the synthesized tab bar.
(source: lightwood.net)
This is how content displays normally. I've scrolled to the very bottom here.
(source: lightwood.net)
This is how it displays when searching. Again, I've scrolled to the very bottom. If I disable the banner ad, I can see that the search display table spreads right down to the tab bar.
(source: lightwood.net)
The key to solving this one was finding out when to change the geometry of the table view. Calling:
[self.searchDisplayController.searchResultsTableView setFrame:someframe];
after creating the UISearchDisplayController was futile. The answer was this delegate method:
-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView {
tableView.frame = someframe;
}
Note, I had also tried -searchDisplayController:didLoadSearchResultsTableView but it did no good in there. You have to wait until it's displayed to resize it.
Also note that if you simply assign tableView.frame = otherTableView.frame, the search results table overlaps its corresponding search bar, so it is impossible to clear or cancel the search!
My final code looked like this:
-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView {
CGRect f = self.masterTableView.frame; // The tableView the search replaces
CGRect s = self.searchDisplayController.searchBar.frame;
CGRect newFrame = CGRectMake(f.origin.x,
f.origin.y + s.size.height,
f.size.width,
f.size.height - s.size.height);
tableView.frame = newFrame;
}
I updated the code to allow for deeper view hierarchies, but the initial frame of the semi-transparent cover view still takes up the entire window below the search bar.
-(void)searchDisplayController: (UISearchDisplayController*)controller
didShowSearchResultsTableView: (UITableView*)tableView
{
if ( [controller.searchBar.superview isKindOfClass: [UITableView class]] )
{
UITableView* staticTableView = (UITableView*)controller.searchBar.superview;
CGRect f = [tableView.superview convertRect: staticTableView.frame fromView: staticTableView.superview];
CGRect s = controller.searchBar.frame;
CGRect newFrame = CGRectMake(f.origin.x,
f.origin.y + s.size.height,
f.size.width,
f.size.height - s.size.height);
tableView.frame = newFrame;
}
}
I'm not sure I completely understand what you're describing, it would be nice to have a screenshot.
It sounds like what's happening is the UITableView is the size of the screen and the banner is overlapping the bottom 50 pixels of it. All UIView children have a frame, bounds, and center properties they inherit from their common UIView parent.
#interface UIView(UIViewGeometry)
// animatable. do not use frame if view is transformed since it will not correctly reflect the actual location of the view. use bounds + center instead.
#property(nonatomic) CGRect frame;
// use bounds/center and not frame if non-identity transform. if bounds dimension is odd, center may be have fractional part
#property(nonatomic) CGRect bounds; // default bounds is zero origin, frame size. animatable
#property(nonatomic) CGPoint center; // center is center of frame. animatable
#property(nonatomic) CGAffineTransform transform; // default is CGAffineTransformIdentity. animatable
// ... from UIView.h
You can manipulate these properties as you like, it sounds like you simply need to adjust the bounds to be 50 pixels smaller than the screen, and do some math to calculate your new center.