Objective C : Getting the height and width of a UIView accurately - objective-c

I having problems getting an accurate reading for heights and widths. So I made this quick and dirty app to test the situation.
Here is the code:
#interface wwfpViewController ()
#property (nonatomic, strong) UIView * box;
#property (nonatomic, strong) UILabel * info;
#end
#implementation wwfpViewController
#synthesize box,info;
- (void)viewDidLoad {
[super viewDidLoad];
box=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[box setBackgroundColor:[UIColor darkGrayColor]];
[box setAutoresizesSubviews:YES];
[box setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
info=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];
[info setTextColor:[UIColor whiteColor]];
[info setBackgroundColor:[UIColor blackColor]];
[info setLineBreakMode:NSLineBreakByWordWrapping];
[info setNumberOfLines:10];
[info setText:#"..."];
[self.view addSubview:box];
[box addSubview:info];
[self updateInfo];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(updateView:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
}
- (void) updateInfo {
CGFloat selfHeight=self.view.frame.size.height;
CGFloat selfWidth=self.view.frame.size.width;
CGFloat boxHeight=box.frame.size.height;
CGFloat boxWidth=box.frame.size.width;
int deviceOrientation=[[UIDevice currentDevice] orientation];
int statusOrientation=[[UIApplication sharedApplication] statusBarOrientation];
NSString * str=[NSString stringWithFormat:#"[height x width] \nself: [%f x %f] \nbox: [%f x %f] \ndevice: %d status: %d",selfHeight,selfWidth,boxHeight,boxWidth,deviceOrientation,statusOrientation];
[info setText:str];
}
- (void) updateView: (NSNotification*) notify {
[self updateInfo];
}
#end
When I test this on an iPad, initially in portrait mode, the info label reports the following:
[height x width]
self: [1004.000000 x 768.000000]
box: [1004.000000 x 768.000000]
device: 0 status: 1
This is correct!
And then when I rotate the iPad to landscape, I get these readings:
[height x width]
self: [768.000000 x 1004.000000]
box: [1004.000000 x 768.000000]
device: 3 status: 3
Actual height x width: 748 x 1024
But when I test this on the iPad when its in landscape orientation, the info label reports:
[height x width]
self: [1024.000000 x 748.000000]
box: [1024.000000 x 748.000000]
device: 0 status: 3
Actual height x width: 748 x 1024
Then when I rotate the iPad to portrait, I get these readings:
[height x width]
self: [748.000000 x 1024.000000]
box: [748.000000 x 1024.000000]
device: 1 status: 1
Actual height x width: 1004 x 768
I rotate it back to landscape and then I get these readings:
[height x width]
self: [768.000000 x 1004.000000]
box: [1004.000000 x 768.000000]
device: 3 status: 3
Actual height x width: 748 x 1024
In all cases the box UIView covers the entire screen, so it is auto adjusting to the orientation changes correctly. These results are consistent from the simulator and testing it on an actual iPad, and I have similar experiences on an iPhone.
After this, I have a few questions:
What am I doing wrong?
Why is the height and width for self.view different from the height and width for box when the two look visually identical?
How can I accurately obtain the overall height and width of the screen or a view, irrespective of orientation changes.
Because [UIDevice ... orientation] reports as zero the first time it is used, should I just ignore it altogether and just stick with [UIApplication ... statusBarOrientation]?

Check the bounds of the views rather than the frame:
CGFloat selfHeight=self.view.bounds.size.height;
CGFloat selfWidth=self.view.bounds.size.width;
CGFloat boxHeight=box.bounds.size.height;
CGFloat boxWidth=box.bounds.size.width;
Also, I would use the UIViewController method for orientation changes and remove the NSNotificationCenter observer.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[self updateInfo];
}
Finally, the first call to get the correct size should be in viewWillAppear as it will be incorrect in viewDidLoad:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self updateInfo];
}

I tried your code and found one mistake here.
Cause of bug- You didn't make app navigationController based in appdelegate. Set your window's rootViewController to navigationController don't know why but viewController's based view doesn't give the correct frame.
My Opinion- Don't use notification here when you have already a method -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation which is call after orientation changed. Well You are using notification then NP this is just my opinion.
One more thing I would like to say
box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
Why don't you simply do
box = [[UIView alloc] initWithFrame:self.view.bounds];
Your Code is okay. Just set your window's rootViewController to navigationController OR tabbarController.
This is Sample Code.

From Apple docs
Discussion When a view’s bounds change, that view automatically
resizes its subviews according to each subview’s autoresizing mask.
You specify the value of this mask by combining the constants
described in UIViewAutoresizing using the C bitwise OR operator.
Combining these constants lets you specify which dimensions of the
view should grow or shrink relative to the superview. The default
value of this property is UIViewAutoresizingNone, which indicates that
the view should not be resized at all.
When more than one option along the same axis is set, the default
behavior is to distribute the size difference proportionally among the
flexible portions. The larger the flexible portion, relative to the
other flexible portions, the more it is likely to grow. For example,
suppose this property includes the UIViewAutoresizingFlexibleWidth and
UIViewAutoresizingFlexibleRightMargin constants but does not include
the UIViewAutoresizingFlexibleLeftMargin constant, thus indicating
that the width of the view’s left margin is fixed but that the view’s
width and right margin may change. Thus, the view appears anchored to
the left side of its superview while both the view width and the gap
to the right of the view increase.
If the autoresizing behaviors do not offer the precise layout that you
need for your views, you can use a custom container view and override
its layoutSubviews method to position your subviews more precisely.
It probably has to do with autoresizing masks read more about it here.

myview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
Working for me

I've made macros vWidth and vHeight that will handle all of this logic properly, with fallbacks:
#define sWidth [[UIScreen mainScreen] bounds].size.width
#define sHeight [[UIScreen mainScreen] bounds].size.height
#define vWidth (\
(^float (void){\
BOOL isClassMethod = [[self class] respondsToSelector:_cmd];\
if (isClassMethod) {\
return sWidth;\
} else {\
float __vWidth = ([self isKindOfClass:[UIViewController class]]?((UIViewController *)self).view.frame.size.width:((UIView *)self).frame.size.width);\
if (!__vWidth) {\
__vWidth = ([self isKindOfClass:[UIViewController class]]?((UIViewController *)self).view.superview.frame.size.width:((UIView *)self).superview.frame.size.width);\
}\
if (!__vWidth) {\
__vWidth = sWidth;\
}\
return __vWidth;\
}\
})()\
)
#define vHeight (\
(^float (void){\
BOOL isClassMethod = [[self class] respondsToSelector:_cmd];\
if (isClassMethod) {\
return sHeight;\
} else {\
float __vHeight = ([self isKindOfClass:[UIViewController class]]?((UIViewController *)self).view.frame.size.height:((UIView *)self).frame.size.height);\
if (!__vHeight) {\
__vHeight = ([self isKindOfClass:[UIViewController class]]?((UIViewController *)self).view.superview.frame.size.height:((UIView *)self).superview.frame.size.height);\
}\
if (!__vHeight) {\
__vHeight = sHeight;\
}\
return __vHeight;\
}\
})()\
)

Related

Cocoa resize window to fit screen

I have 2 monitors, and I'd like to get my videoWindow to be placed and scaled to the size of the second monitor. I'd like to do this programmatically, as the second monitor resolution may change. I'm able to get the window placed in the bottom-left of the second monitor, but I'm not able to scale it to fit.
The warning on this line:
[self.videoWindow setFrame: screenRect];
Is: 'NSWindow' may not respond to 'setFrame'
// inside my .h file
#property (assign) IBOutlet NSWindow *videoWindow;
// inside my .m file
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
[super windowControllerDidLoadNib:aController];
NSRect videoPreviewScreenRect;
NSArray *screenArray = [NSScreen screens];
//Using index of 1, to get secondary monitor
NSScreen *videoPreviewScreen = [screenArray objectAtIndex: 1];
NSRect screenRect = [videoPreviewScreen frame];
videoPreviewScreenRect = [videoPreviewScreen visibleFrame];
// Get and set the screen origin based on the second monitors origin
NSPoint videoScreenOrigin ;
videoScreenOrigin.x = videoPreviewScreenRect.origin.x;
videoScreenOrigin.y = videoPreviewScreenRect.origin.y;
[self.videoWindow setFrameOrigin: videoScreenOrigin];
// **** THIS LINE DOESN'T WORK ****
[self.videoWindow setFrame: screenRect];
[self.videoWindow setBackgroundColor: NSColor.blackColor];
[self.videoWindow display];
[self.videoWindow makeKeyAndOrderFront:nil];
}
I was able to figure out what the issue was.
[self.videoWindow setFrame: screenRect];
needed to be changed to this:
[[self videoWindow] setFrame:screenRect display:YES animate:NO];

How do I size a UITextView to its content on iOS 7?

I've been using the accepted answer here for years.
On iOS 7, the contentSize.height becomes the frame.height-8, regardless of text content.
What's a working method to adjust the height on iOS 7?
I favor this minimal code change: Just add these two lines after addSubview and before grabbing the height of the frame
...
[scrollView1 addSubview: myTextView];
[myTextView sizeToFit]; //added
[myTextView layoutIfNeeded]; //added
CGRect frame = myTextView.frame;
...
This is tested backwards compatible with iOS 6. NOTE that it shrink-wraps the width. If you're just interested in the height and have a fixed width, just grab the new height but set the original width, and it works just as before on both iOS 6 and 7.
(Speculation: it does size to fit on iOS 7 as well, but the layout is updated later or in a separate thread, and that this forces the layout immediately so that its frame is updated in time for using its height value a few lines later in the same thread.)
NOTES:
1) You might or might not have implemented the outer container resize this way. It does seem to be a common snippet, though, and I've used it in my projects.
2) Since sizeToFit seems to work as expected on iOS 7, you likely don't need the premature addSubView. Whether it will still work on iOS 6 then is untested by me.
3) Speculation: The extra layoutIfNeeded mid-thread might be costly. The alternative as I see it is to resize the outer container on the layout callback (fired or not depending on if the OS decides whether layout is needed or not) where the outer container resize will cause another layout update. Both updates might be combined with other layout updates to be more efficient. If you do have such a solution and you can show that it is more efficient, add it as answer and I'll be sure to mention it here.
Since I'm using Auto Layout, I use the value of [textView sizeThatFits:CGSizeMake(textView.frame.size.width, CGFLOAT_MAX)].height to update the constant of the textView's height UILayoutConstraint.
I use an adapted version of madmik's answer that eliminates the fudge factor:
- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
if ([textView respondsToSelector:#selector(snapshotViewAfterScreenUpdates:)])
{
// This is the code for iOS 7. contentSize no longer returns the correct value, so
// we have to calculate it.
//
// This is partly borrowed from HPGrowingTextView, but I've replaced the
// magic fudge factors with the calculated values (having worked out where
// they came from)
CGRect frame = textView.bounds;
// Take account of the padding added around the text.
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:#"\n"])
{
textToMeasure = [NSString stringWithFormat:#"%#-", textView.text];
}
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = #{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
Based on other answers, I made it work(in Swift).
This solves the problem with newline character.
textView.sizeToFit()
textView.layoutIfNeeded()
let height = textView.sizeThatFits(CGSizeMake(textView.frame.size.width, CGFloat.max)).height
textView.contentSize.height = height
Auto Layout is needed.
If you're using Auto Layout, you could create a trivial UITextView subclass that self-sizes the text view height to fit the content:
#interface ContentHeightTextView : UITextView
#end
#interface ContentHeightTextView ()
#property (nonatomic, strong) NSLayoutConstraint *heightConstraint;
#end
#implementation ContentHeightTextView
- (void)layoutSubviews
{
[super layoutSubviews];
CGSize size = [self sizeThatFits:CGSizeMake(self.bounds.size.width, FLT_MAX)];
if (!self.heightConstraint) {
self.heightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0f constant:size.height];
[self addConstraint:self.heightConstraint];
}
self.heightConstraint.constant = size.height;
[super layoutSubviews];
}
#end
Of course, the text view's width and position must be defined by additional constraints configured elsewhere in the program.
If you create this custom text view in IB, give the text view a height constraint in order to satisfy Xcode; just make sure the height constraint created in IB is merely a placeholder (i.e., tick the box that says "Remove at build time").
An alternative way to implement the UITextView subclass is as follows (this implementation might qualify as best practice):
#interface ContentHeightTextView ()
#property (nonatomic, strong) NSLayoutConstraint *heightConstraint;
#end
#implementation ContentHeightTextView
- (void)layoutSubviews
{
[super layoutSubviews];
[self setNeedsUpdateConstraints];
}
- (void)updateConstraints
{
CGSize size = [self sizeThatFits:CGSizeMake(self.bounds.size.width, FLT_MAX)];
if (!self.heightConstraint) {
self.heightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0f constant:size.height];
[self addConstraint:self.heightConstraint];
}
self.heightConstraint.constant = size.height;
[super updateConstraints];
}
#end
If you are using auto-layout, you can use the following UITextView subclass that adds an intrinsic height:
#implementation SelfSizingTextView
- (void)setText:(NSString *)text
{
[super setText:text];
[self invalidateIntrinsicContentSize];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self invalidateIntrinsicContentSize];
}
- (CGSize)intrinsicContentSize
{
CGFloat width = self.frame.size.width;
CGSize size = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return CGSizeMake(UIViewNoIntrinsicMetric, size.height);
}
#end
this method seems to work.
// Code from apple developer forum - #Steve Krulewitz, #Mark Marszal, #Eric Silverberg
- (CGFloat)measureHeight
{
if ([self respondsToSelector:#selector(snapshotViewAfterScreenUpdates:)])
{
CGRect frame = internalTextView.bounds;
CGSize fudgeFactor;
// The padding added around the text on iOS6 and iOS7 is different.
fudgeFactor = CGSizeMake(10.0, 16.0);
frame.size.height -= fudgeFactor.height;
frame.size.width -= fudgeFactor.width;
NSMutableAttributedString* textToMeasure;
if(internalTextView.attributedText && internalTextView.attributedText.length > 0){
textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];
}
else{
textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];
[textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];
}
if ([textToMeasure.string hasSuffix:#"\n"])
{
[textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:#"-" attributes:#{NSFontAttributeName: internalTextView.font}]];
}
// NSAttributedString class method: boundingRectWithSize:options:context is
// available only on ios7.0 sdk.
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return CGRectGetHeight(size) + fudgeFactor.height;
}
else
{
return self.internalTextView.contentSize.height;
}
}
If you're using iOS 7+, you can just turn on auto layout, pin each of the sides of the text view to the edge of its parent view, and it works fine. No additional code needed.
Not sure if this was always the case but the following is true since at least iOS 10.
UITextView implements the intrinsicContentSize property if scrollEnabled == NO. That means you just need to make sure the width of the text view is constrained enough and then you can use the intrinsic content height (either via Auto Layout content hugging/compression resistance priorities or directly using the value during manual layout).
Unfortunately, this behavior is not documented. Apple could have easily saved us all some headaches… no need for an extra height constraint, subclassing, etc.
In iOS 8 you'll in inherit some content offset from the parent, which you need to get rid of as well.
A subclass example
// Originally from https://github.com/Nikita2k/resizableTextView
#import "ResizableTextView.h"
#implementation ResizableTextView
- (void) updateConstraints {
// calculate contentSize manually
// ios7 doesn't calculate it before viewDidAppear and we'll get here before
CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];
// set the height constraint to change textView height
[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
constraint.constant = contentSize.height;
*stop = YES;
}
}];
[super updateConstraints];
}
- (void)setContentOffset:(CGPoint)contentOffset
{
// In iOS 8 we seem to be inheriting the content offset from the parent.
// I'm not interested
}
#end
In storyboard, if using constraints, make sure you are constrained to your superview in the 'ruler' tab of the right-hand pane on xcode for the UITextView. My problem was that I had a constraint of -80 pts on the 'Trailing space to'.
Guys using autolayout and your sizetofit isn't working, then please check your width constraint once. If you had missed the width constraint then the height will be accurate.
No need to use any other API. just one line would fix all the issue.
[_textView sizeToFit];
Here, I was only concerned with height, keeping the width fixed and had missed the width constraint of my TextView in storyboard.
And this was to show up the dynamic content from the services.
Hope this might help..
I wrote a category over UITextView:
- (CGSize)intrinsicContentSize {
return self.contentSize;
}
- (void)setContentSize:(CGSize)contentSize {
[super setContentSize:contentSize];
[self invalidateIntrinsicContentSize];
}
When UIKit sets its contentSize, UITextView adjusts its intrinsic content size. That plays nicely with autolayout.
The answer given by bilobatum worked perfectly With auto layout, i.e subclassing the textview.
If you want to limit the height of the text view add another constraint (I added it using storyboard i.e. height <= 166 (height as per your need))
Then inside subclass reduce the priority of height constraint to 750 (self.heightConstraint.priority = 750) to avoid conflict between height constraint added in subclass and height constraint added on storyboard.

How to get correct frame size of NavigationController in willRotateToInterfaceOrientation?

I'm trying to get correct content frame size which considered the navigationbar's height size.
But if output frame size using NSLog in willRotateTo~ method, shows earlier frame size.
However it shows correct frame size in didRotateFrom~ method.
How to get the frame size like didRotateFrom~ 's size in willRotateTo~ method?
Following is AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
ViewController *rootView = [[[ViewController alloc] init] autorelease];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[[UINavigationController alloc] initWithRootViewController:rootView] autorelease];
} else {
self.viewController = [[[UINavigationController alloc] initWithRootViewController:rootView] autorelease];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
And next is ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
NSLog(#"willRotate size is width : %f height : %f", self.view.frame.size.width, self.view.frame.size.height);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
NSLog(#"didRotate size is width : %f height : %f", self.view.frame.size.width, self.view.frame.size.height);
}
Following is result when rotated to landscape.
/Users/nice7285/Library/Caches/appCode10/DerivedData/testView-d007adbb/Build/Products/Debug-iphonesimulator/testView.app/testView
Simulator session started with process 3896
2012-10-11 04:28:59.719 testView[3896:11303] willRotate size is width : 320.000000 height : 416.000000
2012-10-11 04:29:00.025 testView[3896:11303] didRotate size is width : 480.000000 height : 268.000000
The accepted answer doesn't really solve the problem you're faced with. If you perform your UI changes in didRotateFromInterfaceOrientation, the UI changes happen AFTER the screen has performed its rotation animation. This ends up looking really ugly and sudden.
You should use willAnimateRotationToInterfaceOrientation, which is called after the rotation has happened, bounds have been recalculated, and allows you to setup your UI controls for the animation. This will let you perform a smooth transition from one orientation to another.
The reason self.view.frame in willRotateToInterfaceOrientation is giving you the dimensions before rotation is because the view has not been rotated yet, so the the frame has not been changed yet. The only thing you can know at that point is what orientation you are rotating to. If you want the new dimensions in that function you'll have to hardcode them in yourself. You shouldn't need to do this though as didRotateFromInterfaceOrientation should be able to do everything you want.

Changing Popover view frame on fly

When a popover is displaying how can I make its size variable depending on condition check? Is this functionality supported or not when working with a popover?
Here is my sample for changing frame size:
CGFloat newHeight = 200;
NSRect newFrame = [parentView frame];
newFrame.size.height = newHeight;
NSView* childView = someView;
[parentView setFrame:newFrame];
[self.view addSubview:childView];
Don't know if anything was changed but in 10.9 all you have to do is setContentSize on the popover, e.g.:
[popoverView setFrame:NSMakeRect(0, 0, 581, 581)];
[thePopover setContentSize:popoverView.frame.size];
You need to change the popupwindow.contentViewController property of the NSPopover to a new NSViewController with a different-sized view.
That is, resizing the view's frame will only result in weird drawing problems. To get the popover window to change size, the contentViewController must be changed.
Ideally, you would set up a new view controller which is essentially a copy of your existing NSViewController, but containing a view that is taller/shorter. But in the worst-case scenario, you can do something like this:
gPopoverWindow.contentViewController = [[[NSViewController alloc] initWithNibName: #"tempNibName" bundle: nil] autorelease];
NSView *v = self.view;
NSRect b = [v frame];
b.size.height += 25;
[v setFrame: b];
gPopoverWindow.contentViewController = self;
In my testing, this resulted in the popover beginning a shrink animation (because of being set to the temp view controller), then growing to its new size.

Change the height of NavigationBar and UIBarButtonItem elements inside it in Cocoa Touch

I suppose it's not strictly in line with Apple guidelines but I guess it must be possible somehow. I'd like to change the height of navigation bar inside UINavigationController and the height of UIBarButtonItem elements inside that bar.
Using a trick from this question I managed to change the height of navigation bar but I can see no way of adjusting the height of bar button items.
If anyone knows how to change the size of bar button items, please help me out.
This is my solution. It works very well.
#interface UINavigationBar (CustomHeight)
#end
#implementation UINavigationBar (CustomHeight)
- (CGSize)sizeThatFits:(CGSize)size {
// Change navigation bar height. The height must be even, otherwise there will be a white line above the navigation bar.
CGSize newSize = CGSizeMake(self.frame.size.width, 40);
return newSize;
}
-(void)layoutSubviews {
[super layoutSubviews];
// Make items on navigation bar vertically centered.
int i = 0;
for (UIView *view in self.subviews) {
NSLog(#"%i. %#", i, [view description]);
i++;
if (i == 0)
continue;
float centerY = self.bounds.size.height / 2.0f;
CGPoint center = view.center;
center.y = centerY;
view.center = center;
}
}
Maybe this tutorial about a customized navbar will help you: Recreating the iBooks wood themed navigation bar
If you create a BarButtonItem with a UIImageView you can maybe change the framesize/boundsize of the custom UIImageView
UIImageView* imageView = [[[UIImageView alloc] initWithFrame:navigationController.navigationBar.frame] autorelease];
imageView.contentMode = UIViewContentModeLeft;
imageView.image = [UIImage imageNamed:#"NavBar-iPhone.png"];
[navigationController.navigationBar insertSubview:imageView atIndex:0];
So for your need you would give the -initWithFrame method appropriate values.
static CGFloat const CustomNavigationBarHeight = 74;
#implementation WTNavigationBar
- (CGSize)sizeThatFits:(CGSize)size{
size.width = 1024;
size.height = CustomNavigationBarHeight;
return size;
}
-(void)layoutSubviews {
[super layoutSubviews];
for (UIView *view in self.subviews) {
SFLog(#"view.class=%#",[view class]);
if ([view isKindOfClass:NSClassFromString(#"UINavigationItemButtonView")]) {
float centerY = self.bounds.size.height / 2.0f;
CGPoint center = view.center;
center.y = centerY;
view.center = center;
}
}
}
#end
in my iPad app,which has a fixed landscape orientation,I found I have to hardcode the size's width
I managed to do something similar by subclassing UINavigationBar and overriding -layoutSubviews. The code looks like:
-(void)layoutSubviews {
[super layoutSubviews];
int i = 0;
for (UIView *view in self.subviews) {
NSLog(#"%i. %#", i++, [view description]);
if ([view isKindOfClass:NSClassFromString(#"UINavigationButton")]) {
view.frame = CGRectMake(0, 0, 100, 50);
}
}
}
If you need to know how to subclass UINavigationBar, have a look at this very good answer.
I am not really sure about the NSClassFromString(#"UINavigationButton")] part. It works, but I did this as an experiment, and I'm not sure if this will get approved by Apple. I hope someone with a better knowledge might shed some light.
For the UINavigationbar
In iOS SDK 4.3 and beyond, there is a way (hack) to change the height of the UINavigationBar.
To change the height of UINavigationController, change its frame size in viewWillAppear:animated: function. Then, the height will stay customized throughout whole app.
For the UIBarButtonItems
I've actually run into this myself and the only thing I could come up with was leveraging initWithCustomView and passing in a UIButton with a defined frame.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
/*
* Insert button styling
*/
button.frame = CGRectMake(0, 0, width, height);
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
Otherwise UIBarButtonItem only has a width property that can be set but unfortunately not a height property. Another nifty thing I've done with initWithCustomView is to pass in a toolbar with a button and other things like activity indicators. Hope this helps.
How badly do you want this? And, how thin (or thick) do you want to make your navbar?
One approach would be to set the transform of the navbar to scale and translate it. If you scale it too much the title and button text will look wonky, but if you only need to shave a few pixels you might be allright.
Here's the result of scaling it to be 75% of full height (33 pixels tall):
And the code that produced this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Thin Navigation Bar";
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: #"Press Me" style:UIBarButtonItemStyleBordered target: nil action: NULL ] autorelease];
CGFloat scale = .75;
CGFloat cy = 44.0 - ( 44.0 * scale );
self.navigationController.navigationBar.transform = CGAffineTransformScale( CGAffineTransformMakeTranslation( 0, -cy / 2.0 ), 1.0, scale ) ;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGFloat scale = .75;
CGFloat cy = 44.0 - ( 44.0 * scale );
CGRect r = self.view.frame;
r.origin.y -= cy;
r.size.height += cy;
self.view.frame = r;
}
Now, this does have a number of problems, which may or may not be solvable. #1 is that you're fighting with the UINavigationController to size and position the navbar and the view-controller views. Animating between view controllers that use this technique is likely going to look weird.
I'd be curious if you could solve the related issues...
One last thought: If you dont use a UINavigationController then there really aren't a whole lot of issues with this other than squished text. Or, you could use a navigation controller but hide the default navbar, and add the thin navbar to each of your child-view controller views. You could even subclass UINavigationBar and set the transform from within:
#interface TSThinNavBar : UINavigationBar
{
}
#end
#implementation TSThinNavBar
// assuming we'll always be constructed from a nib
- (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder: aDecoder];
if ( self != nil )
{
CGFloat scale = .75;
CGFloat cy = 44.0 - ( 44.0 * scale );
self.transform = CGAffineTransformScale( CGAffineTransformMakeTranslation( 0, -cy / 2.0 ), 1.0, scale ) ;
}
return self;
}
#end