UIImageView Bounds, Frame - ios

I know there are lots of similar questions here and I checked the famous one, and then grasped the difference between Bounds, and Frame.
Now I have some problem related to them. I played around with them , but it didn't show as I expected.
What I don't understand here is:
Why the frame origin of Y is 44.000000 below the top even I set the UIImageView at the left corner?
Because bounds should be
"The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0)." (Cocoa: What's the difference between the frame and the bounds?)
I thought the frame also should start at the left corner here.
#import "ViewController.h"
#interface ViewController ()
//#property (weak, nonatomic) IBOutlet UIImageView *image;
#property (weak, nonatomic) IBOutlet UIImageView *image2;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//UIImage *imageView = [UIImage imageNamed:#"stanford"];
// self.image.alpha = 1;
// self.image.contentMode = 1;
// self.image.image = imageView;
// [self.image setAlpha:0.1];
// [self.image setContentMode:UIViewContentModeCenter];
// [self.image setImage:imageView];
NSURL *url = [[NSURL alloc] initWithString:#"http://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/Pitbull_2%2C_2012.jpg/472px-Pitbull_2%2C_2012.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imageData = [UIImage imageWithData:data];
[self.image2 setBounds:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.image2 setImage:imageData];
NSLog(#"frame.orign.x:%f,frame.origin.y:%f",self.image2.frame.origin.x,self.image2.frame.origin.y);
}

The 44 magic number value actually comes from the navigation bar :) Whereas the height of the status bar is 20 points.
If you want your image to cover the entire screen then you will need to either get rid of your status bar, or make your status bar translucent so that content can be displayed underneath.
If you don't set your status bar/navigation bar to translucent, then the point of origin 0,0 would start just underneath the bars as you are experiencing now.
status bar is set using
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackTranslucent];
The navigation bar, if you have one displayed can be set using this
theNavigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
Only then will your following code display your content across the full screen
[self.image2 setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]
This is because setting the bars to translucent will have have them displayed as overlays instead.

The 44 comes from the nav bar which takes up that much height

Related

The same dynamic status bar as is in the new Apple Music app

Is it possible to have dynamically coloring statusBar which is in the new Apple Music app ?
Edit:
The new Apple Music app in iOS 8.4 has this feature.
Open the app.
Select and play a song (status bar is white)
Swipe player controller down to see "My music" controller (it has black status bar, maybe you will have to go back in navigation hierarchy).
Now just swipe up/down to see dynamic status bar changes.
Edit 2:
Apple documentation does not seem to let us use it right now (iOS 8.4). Will be available probably in the future with iOS 9.
Edit 3:
Does not seems to be available in iOS 9 yet.
I am 99.99% sure this cannot be done using public API (easily), because I tried myself almost everything there is (i personally also don't think it is some magical method of their status bar, but instead, their application is able to retrieve status bar view and then just apply mask to it).
What I am sure of is that you can do your own StatusBar and there is MTStatusBarOverlay library for that, unfortunately very old one so I can't really tell if that works but it seems that there are still people who use it.
But using the way library does it, I think there might be solution that sure, requires a lot of work, but is doable, though not "live". In a nutshell you would do this:
Take screenshot of top 20 pixels (status bar)
From that screenshot, remove everything that is not black (you can improve it so it searches for black edges, this way you can preserve green battery and transparency) This will make your overlay mask and also fake status bar
Overlay statusbar with : background view masking actual status bar, and the alpha-image you just created
Apply mask to that image, everything that is masked will change color to shades of white
Change height of the mask depending on user scroll
Now you should be able to scroll properly and change the color properly. The only problem that it leaves is that status bar is not alive, but is it really? once you scroll out, you immediately remove your overlay, letting it to refresh. You will do the same when you scroll to the very top, but in that case, you change color of the status bar to white (no animation), so it fits your state. It will be not-live only for a brief period of time.
Hope it helps!
Iterating upon Jiri's answer, this will get you pretty close. Substitute MTStatusBarOverlay with CWStatusBarNotification. To handle the modal transition between view controllers, I'm using MusicPlayerTransition. We're assuming an imageView: "art" in self.view with frame:CGRect(0, 0, self.view.bounds.size.width, self.view.bounds.size.width). Needs a little massaging, but you get the gist. Note: Though we're not "live," the most we'll ever be off is one second, and battery color is not preserved. Also, you'll need to set the animation time in CWStatusBarNotification.m to zero. (notificationAnimationDuration property).
#import "CWStatusBarNotification.h"
#define kStatusTextOffset 5.4 // (rough guess of) space between window's origin.y and status bar label's origin.y
#interface M_Player () <UIGestureRecognizerDelegate>
#property (retain) UIView *fakeStatusBarView;
#property (retain) CWStatusBarNotification *fakeStatusBar;
#property (retain) UIImageView *statusImgView;
#property (retain) UIImageView *statusImgViewCopy;
#property (retain) UIWindow *window;
#property (strong, nonatomic) NSTimer *statusTimer;
#end
#implementation M_Player
#synthesisze fakeStatusBarView, fakeStatusBar, statusImgView, statusImgViewCopy, window, statusTimer;
-(void)viewDidLoad{
self.window = [[UIApplication sharedApplication] delegate].window;
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handleStatusBarDrag:)];
pan.delegate = self;
[self.view addGestureRecognizer:pan];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if (!fakeStatusBar){
[self buildFakeStatusBar];
}
if (!statusTimer) {
[self setupStatusBarImageUpdateTimer];
}
// optional
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
[self setNeedsStatusBarAppearanceUpdate];
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[self destroyStatusBarImageUpdateTimer];
}
-(void)destroyFakeStatusBar{
[statusImgView removeFromSuperview];
statusImgView = nil;
[fakeStatusBarView removeFromSuperview];
fakeStatusBarView = nil;
fakeStatusBar = nil;
}
-(void)buildFakeStatusBar{
UIWindow *statusBarWindow = [[UIApplication sharedApplication] valueForKey:#"_statusBarWindow"]; // This window is actually still fullscreen. So we need to capture just the top 20 points.
UIGraphicsBeginImageContext(self.view.bounds.size);
[statusBarWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, 20);
CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], rect);
UIImage *statusImg = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
statusImg = [statusImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; // This allows us to set the status bar content's color via the imageView's .tintColor property
statusImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
statusImgView.image = statusImg;
statusImgView.tintColor = [UIColor colorWithWhite:0.859 alpha:1.000]; // any color you want
statusImgViewCopy = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
statusImgViewCopy.image = statusImg;
statusImgViewCopy.tintColor = statusImgView.tintColor;
fakeStatusBarView = nil;
fakeStatusBar = nil;
fakeStatusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
[fakeStatusBarView addSubview:statusImgView];
fakeStatusBar = [CWStatusBarNotification new];
fakeStatusBar.notificationStyle = CWNotificationStyleStatusBarNotification;
[fakeStatusBar displayNotificationWithView:fakeStatusBarView forDuration:CGFLOAT_MAX];
}
-(void)handleStatusBarDrag:(UIPanGestureRecognizer*)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
}
if (gestureRecognizer.state == UIGestureRecognizerStateChanged){
CGPoint convertedPoint = [self.window convertPoint:art.frame.origin fromView:self.view];
CGFloat originY = convertedPoint.y - kStatusTextOffset;
if (originY > 0 && originY <= 10) { // the range of change we're interested in
//NSLog(#"originY:%f statusImgView.frame:%#", originY, NSStringFromCGRect(statusImgView.frame));
// render in context from new originY using our untouched copy as reference view
UIGraphicsBeginImageContext(self.view.bounds.size);
[statusImgViewCopy.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rect = CGRectMake(0, kStatusTextOffset + originY, self.view.bounds.size.width, 20);
CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], rect);
UIImage *statusImg = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
statusImgView.image = statusImg;
statusImgView.transform = CGAffineTransformMakeTranslation(0, kStatusTextOffset + originY);
}
// destroy
if (originY > 90) {
[self destroyFakeStatusBar];
}
}
if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
To keep your status bar screenshots in sync with the actual status bar, setup your timer. Fire it in viewWillAppear, and kill it in viewDidDisappear.
-(void)setupStatusBarImageUpdateTimer{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^(){
// main thread
if (!statusTimer) {
statusTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(handleStatusTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:statusTimer forMode:NSRunLoopCommonModes];
}
});
});
}
-(void)destroyStatusBarImageUpdateTimer{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^(){
// main thread
[statusTimer invalidate];
statusTimer = nil;
});
});
}
-(void)handleStatusTimer:(NSTimer*)timer{
UIWindow *statusBarWindow = [[UIApplication sharedApplication] valueForKey:#"_statusBarWindow"];
UIGraphicsBeginImageContext(CGSizeMake(self.view.bounds.size.width, 20));
[statusBarWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, 20);
CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], rect);
UIImage *statusImg = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
statusImg = [statusImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
statusImgViewCopy.image = statusImg;
}
Because we have a strong reference to the timer and setup and invalidation happens on the same thread, there's no worrying about the timer failing to invalidate.
The final result should look something like this:
At first glance it looked like a manipulation of a snapshot from the status bar but the status bar is live on both ends so that's not the case.
At second glance it looked like some new api that was introduced in iOS 8.4 but after reviewing the api I couldn't find anything related to that.
It seems very odd to me that apple would use private apis in her own app. This would results some really bad example for developers but then again, there is nothing public that will let you have two styles on your live statusbar.
This leaves us with private api or black magic.
Thinking about how to implement this without private APIs.
I think there may be a solution with second UIWindow overlaying your statusBar.
Adding view on StatusBar in iPhone
Maybe it's possible to make screenshots of status bar constantly (taken from your main Window) to the image, apply some filter on it and display this 'fake statusbar image' on your second window (above 'real' statusBar).
And you can do what you want with the second "fake" statusbar.

Custom UINavigationBar with custom height in center

I have reviewed almost all questions on OS related to custom NavigationBar but unable to find those solutions helpful. Please have a look on following screenshot,
Red portion represents an icon (small image) in the center of navigationBar.
Please suggest some solution. Thanks in advance.
EDIT: I want to implement that for all UINavigationBar in app. I mean on each view
NOTE: I do not know who is down voting my question but i want to ask a question from those persons. Do you have any solution for my problem? If not, then why you are down voting my question? I will not be able to get help in this way. It's totally wrong.
You can subclass UINavigationBar.
#import "VSNavigationBar.h"
#interface VSNavigationBar ()
#property (nonatomic, weak) UIView *noseView;
#end
#implementation VSNavigationBar
-(void)layoutSubviews
{
[super layoutSubviews];
static CGFloat width = 80;
if (!_noseView) {
UIView *noseView = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.size.width / 2 - width / 2, 0, width, width)];
self.noseView = noseView;
self.noseView.backgroundColor = self.barTintColor;
self.noseView.layer.cornerRadius = self.noseView.frame.size.width / 2;
[self addSubview:_noseView];
}
_noseView.frame = CGRectMake(self.bounds.size.width / 2 - width / 2, 0, width, width);
}
#end
And in your Storyboard you would select the NavigationController scene, in the tree view on the left select Navigation Bar and on the right side select the identity inspector and change the class to the subclass.
you need to create an image that looks like central part of the image you have provided and say -
UIImage *image = [UIImage imageNamed: #"logo.png"];
UIImageView *imageview = [[UIImageView alloc] initWithImage: image];
self.navigationItem.titleView = image view;
If you are trying to get circular effect like the bottom of the image you provided, in that case you need to have same image as above and set it as background image of navbar -
[navigationBar setBackgroundImage:[UIImage imageNamed: #"yourImage"] forBarMetrics:UIBarMetricsDefault];

Need to change size and location of CALayer class objects

I am trying to copy all of the functionality of this example app provided by Apple called AVCam: https://developer.apple.com/library/ios/samplecode/AVCam/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010112-Intro-DontLinkElementID_2
The only thing I am having trouble with is changing the size and location of a UIView object. The problem is I am using apple's sample code and it's just not making sense for me.
Apple provides this sample VC that I have called MediaCapturePreviewView. Here is the header file code:
#import <UIKit/UIKit.h>
#class AVCaptureSession;
#interface MediaCapturePreviewView : UIView
#property (nonatomic) AVCaptureSession *session;
#end
Here is it's main file code:
#import "MediaCapturePreviewView.h"
#import <AVFoundation/AVFoundation.h>
#implementation MediaCapturePreviewView
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
+ (Class)layerClass
{
return [AVCaptureVideoPreviewLayer class];
}
- (AVCaptureSession *)session
{
return [(AVCaptureVideoPreviewLayer *)[self layer] session];
}
- (void)setSession:(AVCaptureSession *)session
{
[(AVCaptureVideoPreviewLayer *)[self layer] setSession:session];
}
#end
Then in my app's central View Controller, I have imported the header file of "MediaCapturePreviewView" that I just showed you. Last but not least, in my central view controller's main file I have an IBOutlet in the interface area that looks like this:
#property (nonatomic, weak) IBOutlet MediaCapturePreviewView *previewView;
The above IBOutlet has been connected to a UIView object in Interface Builder that covers the entire iPhone screen.
And then here is a small example of how previewView is used when you tap the "take a picture" button:
- (IBAction)snapStillImage:(id)sender
{
dispatch_async([self sessionQueue], ^{
// Update the orientation on the still image output video connection before capturing.
[[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
I have tried adding in this code right after the above method calls but it is not helping:
_previewView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.frame.size.height/2);
I know that you can edit properties for CALayer class objects like frame, bounds, and position but I'm just stuck and don't know where exactly I need to edit these things.
This is what the current UIView looks like when taking a picture:
And this is what I need it to look like:
I basically need it to take up exactly the top 50% of the iPhone's screen.
Any help is greatly appreciated thank you.
The video has a default capture ratio which fits the iPhone's screen. If you try to scale it to a different ratio (such as half screen) you will get a distorted image or a cropped one.
In order to achieve what you're trying to do I think it would be easier to just cover up half of the screen with a UIView containing the controls you want (such as take a photo button) and then just crop the captured full screen image to half its size with something like this:
CGRect clippedRect = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height/2.0);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

View background as the current set background image?

I'm developing an app which takes a common background for most of the views displayed on the screen, so let's say I have this background image for my app:
Now imagine I add a table view and I want my table view section view background to be the app background image specific part it should match in its current position. How do I achieve that effect? I tried setting alpha to 0 but obviously this is what happens when I scroll my table:
What I want it to look like always:
What happens when I scroll:
I also tried setting background image layer's mask property but since it only works for one view layer it's not the right thing to do in this case.
I know I'm not explaining myself really well, but I hope you understand at least what I want to do.
You can do this by cutting out the part of the image you need then setting it has the background for the nav bar.
Here is a category to cut out part of the image:
.h
#import <UIKit/UIKit.h>
#interface UIImage (Crop)
-(UIImage*)cropFromRect:(CGRect)fromRect;
#end
.m
#import "UIImage+Crop.h"
#implementation UIImage (Crop)
-(UIImage*)cropFromRect:(CGRect)fromRect
{
fromRect = CGRectMake(fromRect.origin.x * self.scale,
fromRect.origin.y * self.scale,
fromRect.size.width * self.scale,
fromRect.size.height * self.scale);
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, fromRect);
UIImage* crop = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imageRef);
return crop;
}
#end
Then in your viewDidLoad:
//Cut out part of image where nav bar sits
UIImage *navBG = [[UIImage imageNamed:#"cVyuX.png"] cropFromRect:CGRectMake(0, 20, 320, 44)];
//Set nav bar image
[[UINavigationBar appearance] setBackgroundImage:navBG forBarMetrics:UIBarMetricsDefault];
//Remove gray seperator
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
I was able to produce this:
Set your tableView background to be clearColor and do the same for your tableViewCells. Then you must hide the separator lines.
tableView.backgroundColor = [UIColor clearColor];
//in your tableView cellForRowPath method
cell.backgroundColor = [UIColor clearColor];
cell.separatorStyle = UITableViewCellSeparatorStyleNone;

Centering and sizeToFit subview at run time and during orientation changes

The is the first of several problems I'm having setting up some UIViews and subviews. I have a UIView that is dynamically positioned on screen at run time. That UIView (master) contains another UIView (child) which wraps a UIImageView and a UILabel. Here are the requirements I have for this arrangement:
The child UIView must stay centered in the master UIView when the device rotates.
The text in the UILabel can be very long or very short and the child UIView with the image and text must still remain centered.
I would like to avoid subclassing UIView to handle this scenario and I would also like to avoid any frame/positioning code in willRotateToInterfaceOrientation. I'd like to handle all of this with some autoresizingMask settings in I.B. and maybe a little forced resizing code, if possible.
This is the arrangement of controls in Interface Builder(highlighted in red):
With Interface Builder, the autoresizingMask properties have been set like so, for the described controls
UIView (master): Flexible top margin, Flexible left margin, Flexible right margin, Flexible width
UIView (child): Flexible top margin, Flexible bottom margin, Flexible left margin, Flexible right margin, Flexible width, Flexible height. (All modes, except None)
UIImageView: Flexible right margin
UILabel: Flexible right margin
This is the view (red bar with image and text) after it's been added programmatically at run time while in portrait mode:
The master UIView's background is a light-red colored image. The child UIView's background is slightly darker than that, and the UILabel's background is even darker. I colored them so that I could see their bounds as the app responded to rotation.
It's clear to me that:
It is not centered but ...
After changing the text from it's default value in I.B from "There is no data in this map extent." to "TEST1, 123." the label contracts correctly.
This is the view after it's been added while in portrait and then rotated to landscape mode:
From here I can see that:
It is still not centered and perhaps at its original frame origin prior to rotation
The UIView (child) has expanded to fill more of the screen when it shouldn't.
The UIView (master) has properly expanded to fill the screen width.
This is the code that got me where I am now. I call the method showNoDataStatusView from viewDidLoad:
// Assuming
#define kStatusViewHeight 20
- (void)showNoDataStatusView {
if (!self.noDataStatusView.superview) {
self.noDataStatusView.frame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.noDataStatusView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgRedStatus.png"]];
// Position the label view in the center
self.noDataStatusLabelView.center = CGPointMake(self.noDataStatusView.frame.size.width/2,
self.noDataStatusView.frame.size.height/2);
// Test different text
self.noDataStatusLabel.text = #"Testing, 123.";
// Size to fit label
[self.noDataStatusLabel sizeToFit];
// Test the status label view resizing
[self.noDataStatusLabelView resizeToFitSubviews];
// Add view as subview
[self.view addSubview:self.noDataStatusView];
}
}
Please note the following:
resizeToFitSubviews is a category I placed on UIView once I found that UIView's won't automatically resize to fit their subviews even when you call sizeToFit. This question, and this question explained the issue. See the code for the category, below.
I have thought about creating a UIView subclass that handles all this logic for me, but it seems like overkill. It should be simple to arrange this in I.B. right?
I have tried setting every resizing mask setting in the book, as well as adjusting the order in which the resizing of the label and view occur as well as the point at which the master view is added as a subview. Nothing seems to be working as I get odd results every time.
UIView resizeToFitSubviews category implementation method:
-(void)resizeToFitSubviews
{
float width = 0;
float height = 0;
// Loop through subviews to determine max height/width
for (UIView *v in [self subviews]) {
float fw = v.frame.origin.x + v.frame.size.width;
float fh = v.frame.origin.y + v.frame.size.height;
width = MAX(fw, width);
height = MAX(fh, height);
}
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, width, height)];
}
What I want to know is why the UIView (child) is not properly centered after it's superview is added to the view hierarchy. It looks as though its got the proper width, but is somehow retaining the frame it had in I.B. when the label read "There is no data in this map extent."
I want to also know why it's not centered after device rotation and whether or not the approach I'm taking here is wise. Perhaps this is causing the other issues I'm having. Any UIView layout help here would be greatly appreciated.
Thanks!
If you are able to target iOS 6 you could use the new Auto Layout functionality to make this much much easier to manage - I've been reading a great tutorial by Ray Wenderlich that seems to be perfect to solve the problem you are seeing.
The problem here is that my UIView (master) does not layout it's subviews automatically when the device rotates and the "springs & struts" layout method used to position the image and interior UIView was inefficient. I solved the problem by doing two things.
I got rid of the internal UIView (child) instance, leaving only the UIView (master) and inside of that a UILabel and UIImageView.
I then created a UIView subclass called StatusView and in it I implement the layoutSubviews method. In its constructor I add a UIImageView and UILabel and position them dynamically. The UILabel is positioned first based on the size of the text and then the UIImageView is placed just to the left of it and vertically centered. That's it. In layoutSubviews I ensure that the positions of the elements are adjusted for the new frame.
Additionally, since I need to swap the background, message and possibly the image in some circumstances, it made sense to go with a custom class. There may be memory issues here/there but I'll iron them out when I run through this with the profiling tool.
Finally, I'm not totally certain if this code is rock solid but it does work. I don't know if I need the layout code in my init method, either. Layout subviews seems to be called shortly after the view is added as a subview.
Here's my class header:
#import <UIKit/UIKit.h>
typedef enum {
StatusViewRecordCountType = 0,
StatusViewReachedMaxRecordCountType = 1,
StatusViewZoomInType = 2,
StatusViewConnectionLostType = 3,
StatusViewConnectionFoundType = 4,
StatusViewNoDataFoundType = 5,
StatusViewGeographyIntersectionsType = 6,
StatusViewRetreivingRecordsType = 7
} StatusViewType;
#interface StatusView : UIView
#property (strong, nonatomic) NSString *statusMessage;
#property (nonatomic) StatusViewType statusViewType;
- (id)initWithFrame:(CGRect)frame message:(NSString*)message type:(StatusViewType)type;
#end
... and implementation:
#import "StatusView.h"
#define kConstrainSizeWidthOffset 10
#define kImageBufferWidth 15
#interface StatusView ()
#property (nonatomic, strong) UILabel *statusMessageLabel;
#property (nonatomic, strong) UIFont *statusMessageFont;
#property (nonatomic, strong) UIImage *statusImage;
#property (nonatomic, strong) UIImageView *statusImageView;
#end
#implementation StatusView
#synthesize statusMessageLabel = _statusMessageLabel;
#synthesize statusMessageFont = _statusMessageFont;
#synthesize statusImageView = _statusImageView;
#synthesize statusMessage = _statusMessage;
#synthesize statusViewType = _statusViewType;
#synthesize statusImage = _statusImage;
- (id)initWithFrame:(CGRect)frame message:(NSString *)message type:(StatusViewType)type {
self = [super initWithFrame:frame];
if (self) {
if (message != nil) {
_statusMessage = message;
_statusMessageFont = [UIFont fontWithName:#"Avenir-Roman" size:15.0];
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel = [[UILabel alloc] initWithFrame:labelFrame];
_statusMessageLabel.backgroundColor = [UIColor clearColor];
_statusMessageLabel.textColor = [UIColor whiteColor];
_statusMessageLabel.font = _statusMessageFont;
// Set shadow and color
_statusMessageLabel.shadowOffset = CGSizeMake(0, 1);
_statusMessageLabel.shadowColor = [UIColor blackColor];
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
// Flex both the width and height as well as left and right margins
_statusMessageLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
// Set label text
_statusMessageLabel.text = _statusMessage;
[self addSubview:_statusMessageLabel];
}
self.statusViewType = type;
if (_statusImage != nil) {
// Create image view
_statusImageView = [[UIImageView alloc] initWithImage:_statusImage];
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
[self addSubview:_statusImageView];
}
}
return self;
}
- (void)layoutSubviews {
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel.frame = labelFrame;
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
if (_statusImageView != nil) {
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
}
}
#pragma mark - Custom setters
- (void)setStatusMessage:(NSString *)message {
if (_statusMessage == message) return;
_statusMessage = message;
_statusMessageLabel.text = _statusMessage;
// Force layout of subviews
[self setNeedsLayout];
[self layoutIfNeeded];
}
- (void)setStatusViewType:(StatusViewType)statusViewType {
_statusViewType = statusViewType;
UIColor *bgColor = nil;
switch (_statusViewType) {
// Changes background and image based on type
}
self.backgroundColor = bgColor;
if (_statusImageView != nil) {
_statusImageView.image = _statusImage;
}
}
#end
Then in my view controller I can do this:
CGRect statusFrame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.staticStatusView = [[StatusView alloc] initWithFrame:statusFrame message:#"600 records found :)" type:StatusViewRecordCountType];
self.staticStatusView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:self.staticStatusView];
... and later on I can change it up by doing this:
self.staticStatusView.statusMessage = #"No data was found here";
self.staticStatusView.statusViewType = StatusViewNoDataFoundType;
Now I've got a reusable class rather than 12 UIView instances floating around my NIB with various settings and properties.

Resources