Centering a dynamically-sized `titleView` in navigation bar without autolayout - ios

I'm new to iOS layouts, and I'm trying to programmatically centre a custom view (actually a React Native RCTRootView which extends UIView, if that's relevant) which has intrinsically sized, dynamic content (defined over in javascript land).
I've seen solutions overriding intrinsicallySizedContent but that seems to be only relevant to auto-layout, which isn't used by RN. The only way I've been able measure the size of the RCTRootView's content is by adding it to a view, and waiting over several passes of layoutSubViews until its frame has a size. That led me to the following effort:
Attempt: Wrap and set wrapper size in layoutSubViews
I'm wrapping the RCTRootView in another UIView and trying to override layoutSubViews, setting the size of my wrapping frame once I have the size of the react native content.
My wrapper is created and added to the navigation bar in my UIViewController like this:
RCTBridge *bridge = ((RCTRootView*)self.view).bridge;
RCTRootView *reactView = [[RCTRootView alloc] initWithBridge:bridge moduleName:navBarCustomView initialProperties:initialProps];
RCCCustomTitleView *titleView = [[TitleWrapperView alloc] initWithFrame:self.navigationController.navigationBar.bounds subView:reactView];
self.navigationItem.titleView = titleView;
self.navigationItem.titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
And the wrapper is implemented like this:
#import "TitleWrapperView.h"
#import <React/RCTRootView.h>
#interface TitleWrapperView ()
#property (nonatomic, strong) RCTRootView *subView;
#end
#implementation TitleWrapperView // Extends UIView
-(instancetype)initWithFrame:(CGRect)frame subView:(RCTRootView*)subView {
self = [super initWithFrame:frame];
if (self) {
self.subView = subView;
self.subView.sizeFlexibility = RCTRootViewSizeFlexibilityWidthAndHeight;
self.clipsToBounds = true;
// Prevent the wrapper from being so large initially as to squash the '< Back' button down to '<'
self.frame = CGRectZero;
[self addSubview:subView];
}
return self;
}
-(void)layoutSubviews {
[super layoutSubviews];
CGRect contentViewFrame = self.subView.contentView.frame;
if (contentViewFrame.size.width > 0) {
// Once we have a measurement for the sub-view's content, set the wrapper's frame
if (self.frame.size.width != contentViewFrame.size.width) {
self.frame = contentViewFrame;
}
}
}
#end
That works a treat on iOS 11+, but not on iOS 10.3, where when the screen containing the custom nav (the red box) is pushed, the navigation transition animates the titleView over towards the top left, rather than into the centre (the end position, which is correct) as I'd hope:
Other approaches?
There might be a way to overcome the iOS 10 glitch above (and I'd love to hear it) but I'm fairly certain there must be a better approach. Is is possible to allow an arbitrary, complex view to lay itself out and get its measurement before adding it to a parent? I've also tried overriding sizeThatFits in my wrapper, which is called by the navigation bar, and requesting the size of my RCTRootView using [subView sizeThatFits: myLargeContainer], but I get 0,0 back.
I'm at a loss - any pointers are appreciated.

Related

programmatically added uiview does not displayed

I'm trying to create a uiview programmatically and adding it to a stack_view which was also programmatically created and added to the view.
This is the code:
the .h
#interface ViewController : UIViewController
#property (strong, nonatomic, nullable) UIStackView * stack;
#end
the .m
#implementation viewController
#synthesize stack;
- (void) viewDidLoad {
[super viewDidLoad];
CGRect * vframe = self.view.frame;
// - Option 1
stack = [[UIStackView alloc] initWithFrame:CGRectMake(vframe.origin.x, 100,vframe.size.width,300)];
stack.axis = UILayoutConstraintAxisHorizontal;
stack.aligment = UIStackViewAligmentTop;
stack.distribution = UIStackViewDistributionFill;
[self.vew addSubview:stack];
// Option 2
// stack.traslateAutorezisingMaskIntoConstraints = NO;
// [stack.leadingAnchor constraintsEqualToAnchor: self.view.leadingAnchor].active = YES;
// [stack.topAnchor constraintsEqualToAnchor: self.view.topAnchor constant: 100].active = YES;
UIView * pView = [[UIView alloc] init];
pView.backgroundColor = [UIColor blueColor];
[stack addArrangedSubview:pView];
}
#end
This code does not show the view at all, I've tried to prove the option 2 (appeared commented in the code) and it does not work either. It is not supposed that the view, upon inserted in the stack, will get the size of the stack, since the distribution of it is "Fill"?. None of this work either even if I define Pview with frame=CGRectMakeRect(0,0,self.view.frame.size.width,100), for instance.
What am I doing wrong?
EDIT: I already fix the misspelled in the code (the * in the CGRect and the self.vew instead of self.view). I made these mistakes when I was manually copying the code, I did not copy and paste the code; tha's is why is made them and that's why the original code compile well
To diagnose this first test the pView. Init it with a fixed size like CGRectMake(100,100,100,100) and add it directly to the viewContoller's view. You should be able to see it no problem if not you have a deeper issue.
If that goes well try the UIStackView with a fixed size. Color its background to see it better if you need. If you still dont see it then double check it still has the correct frame in viewDidAppear of the viewController. It might have adjusted itself after creation. If that is correct go to Debug -> View Debugging -> Capture View Heirachy in Xcode after you have it up in the simulator. If you dont see it there then there was an issue adding it as a subview (note the typo [self.vew addSubview:stack];)
If that goes well then there is a problem with [stack addArrangedSubview:pView]. Similar to the previous step, loop through all the arrangedSubviews in UIStackView in viewDidAppear of its viewController.
CGRect vframe = self.view.frame;
In viewDidLoad, your self.view.frame has not been calculated yet. You need to do this in viewDidLayoutSubviews or viewDidAppear. both of these will get called multiple times so be careful.
EDIT:
As suggested below by danh (I overlooked it) you should remove * from the above line , also, you have several misspelling in your code, don't know how this code really even compiled for you.

iOS - UIView Always on Front without BringSubviewToFront

Can I have some UIView which will always appear on top in iOS?
There are lots of addSubview in my project but I need to have one small view which will always appear. SO is there any other option than
[self.view bringSubViewToFront:myView];
Thanks
One more option (especially if you want to overlap several screens, with logo for example) - separate UIWindow. Use windowLevel to set the level of new window.
UILabel *devLabel = [UILabel new];
devLabel.text = #" DEV ";
devLabel.font = [UIFont systemFontOfSize:10];
devLabel.textColor = [UIColor grayColor];
[devLabel sizeToFit];
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
static UIWindow *notificationWindow;
notificationWindow = [[UIWindow alloc] initWithFrame:
CGRectMake(screenSize.width - devLabel.width, screenSize.height - devLabel.height,
devLabel.width, devLabel.height)];
notificationWindow.backgroundColor = [UIColor clearColor];
notificationWindow.userInteractionEnabled = NO;
notificationWindow.windowLevel = UIWindowLevelStatusBar;
notificationWindow.rootViewController = [UIViewController new];
[notificationWindow.rootViewController.view addSubview:devLabel];
notificationWindow.hidden = NO;
Another option is set layer.zPosition of your UIView.
You need to add
#import <QuartzCore/QuartzCore.h>
Framework to your .m file.
And set such like
myCustomView.layer.zPosition = 101;// set maximum value as per your requirement.
For more information about layer.zPosition read this documentation.
Discussion
The default value of this property is 0. Changing the value of this property changes the the front-to-back ordering of layers onscreen. This can affect the visibility of layers whose frame rectangles overlap.
The other option is to add other subviews below this always-on-top subview. For example:
[self.view insertSubview:subview belowSubview:_topSubview];
There's no solution with Interface Builder if you search for this kind. It should be done programmatically. If you don't want to use bringSubviewToFront: everytime, just insert other subviews below this one.
Many times your view did not appear in viewDidLoad or, if your view comes from parentViewController (for example in many transitions like modal segue..) your can see parentViewController only in viewDidAppear so:
Try to put bringSubviewToFront in :
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.view bringSubViewToFront:myView];
// or if your view is attached in parentViewController
[self.parentViewController.view bringSubViewToFront:myView];
}
Good luck!

Instantiate several draggable tiles from Storyboard - test code and screenshots attached

In Xcode 5 I have created a single view iPhone app and checked it into GitHub.
I would like to display 5 draggable tiles with random letters and their values.
I would prefer to define the tile inside the Storyboard and then instantiate it (5 times) from there - because this way it is easy for me to edit the tile (for example move the labels inside the tile).
Currently my project looks like this (here fullscreen of Xcode):
At the moment have just one tile in the Storyboard and it is draggable:
I have added a Tile class, but don't know how to connect its outlets (because I can only ctrl-drag to the ViewController.h, but not to the Tile.h):
Here Tile.h:
#interface Tile : UIView
// XXX How to connect the outlets?
#property (weak, nonatomic) IBOutlet UIImageView *background;
#property (weak, nonatomic) IBOutlet UILabel *letter;
#property (weak, nonatomic) IBOutlet UILabel *value;
#end
And Tile.m:
#import "Tile.h"
static NSString* const kLetters = #"ABCDEFGHIJKLMNOPQRSTUWVXYZ";
static UIImage* kTile;
static UIImage* kDragged;
#implementation Tile
+ (void)initialize
{
// do not run for derived classes
if (self != [Tile class])
return;
kTile = [UIImage imageNamed:#"tile"];
kDragged = [UIImage imageNamed:#"dragged"];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSString* randomLetter = [kLetters substringWithRange:[kLetters rangeOfComposedCharacterSequenceAtIndex:random()%[kLetters length]]];
int randomInteger = (int)arc4random_uniform(10);
_background.image = kTile;
_letter.text = randomLetter;
_value.text = [NSString stringWithFormat:#"%d", randomInteger];
}
return self;
}
#end
Finally ViewController.m:
#import "ViewController.h"
static int const kNumTiles = 5;
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
for (int i = 0; i < kNumTiles; i++) {
// TODO: add a Tile to the VC here
}
}
- (IBAction)dragTile:(UIPanGestureRecognizer *)recognizer
{
UIView *tile = recognizer.view;
if (recognizer.state == UIGestureRecognizerStateBegan ||
recognizer.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [recognizer translationInView:[tile superview]];
[tile setCenter:CGPointMake(tile.center.x + translation.x,
tile.center.y + translation.y)];
[recognizer setTranslation:CGPointZero inView:tile.superview];
// TODO: instead of tile.png display dragged.png with shadow
}
}
#end
In the latter file, I don't know
How to instantiate 5 tiles from the Storyboard?
How to display shadow (the dragged.png) when dragging a tile?
UPDATE:
As suggested by Fogmeister (thanks!) I have added a new file Tile.xib
(Selected in Xcode menu: File -> New -> File... -> User Interface -> View)
Then I've set the Custom Class to Tile, but where can I set the (square) dimensions?
(Here fullscreen)
UPDATE 2:
For Tile.xib I've set Size to Freeform, Drawing to Opaque and dimensions to 100 x 100 (here fullscreen):
Why does my custom UIView have white corners? How to make the background transparent?
Also I wonder, how to switch of the display of the battery in Interface Builder?
How to instantiate 5 tiles from the storyboard.
I think the thing to realise here is that storyboards are not the solution for everything but rather should be used with the suite of tools that already existed.
For instance. Creating multiple instances of views in this way is not something that can be done very well using Storyboards. Storyboards should be thought of as providing the overall backbone of the app.
To do this I'd do it one of two ways...
First Way
Create a new NIB file called Tile.xib and layout your single Tile view in there. Connect the outlets up to the Tile class file. Now in your view controller you can load the Tile class using the nib for layout...
Tile *tile = [[[NSBundle mainBundle] loadNibNamed:#"Tile" owner:self options:nil] firstObject];
tile.frame = //blah
[self.view addSubview:tile];
Second Way
Or forget the nib and load the Tile view all in code in your Tile.m file. Then load it like...
Tile *tile = [[Tile alloc] initWithFrame:someFrame];
[self.view addSubview:tile];
How to display shadow (the dragged.png) when dragging a tile?
For this you need to set the shadow on the layer of the tile view...
tile.layer.shadowColor = [UIColor blackColor].CGColor;
tile.layer.shadowRadius = 4.0;
// etc...
You can read more about shadows here...
https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004500-CH1-SW78
Edited after comment
To do this I would have a BOOL property on Tile.h called something like isDragging. Or even an enum called TileState with TileStateDragging and TileStateStatic.
Then have a method...
- (void)setDragging:(BOOL)dragging
{
_dragging = dragging;
if (_dragging) {
//set to the shadow image.
} else {
//set the none shadow image.
}
}
Some other things to note
Currently you have code inside initWithFrame of the Tile class but you are loading the class using a nib (storyboard in this case). This will run the method initWithCoder not initWithFrame so this code will never get run.
If you want to run code when the class is created you might be best using the method awakeFromNib instead.
The problem seems to be solved but I'd still put in my 2 pennies and show you another solution just so that you have a complete picture. You can instantiate a UICollectionView in the storyboard and define a UICollectionViewCell prototype inline (in the storyboard). The cell is also a regular view so you can put your complete tile view hierarchy in there (all in the storyboard). You will then need to define a custom UICollectionViewLayout subclass that will provide layout attributes for the tiles (those can change over time and may be animated just like any other views). The use of collection view will impose a structure on your code that will:
scale to any number of tiles,
support tasks like animated insertion and deletion of the tiles (you still need to write code in your layout subclass but all the APIs are already defined for you and you don't need to invent the design),
separate the layout code from game logic (which is of course not exclusive to this solution but still nice to get without even thinking of it :).
This looks like an overkill for this particular toy project but you might need to consider collection view for more complex situations.

Centering a custom sized UIModalPresentationPageSheet?

We can create formsheet views of non-standard size using the following bit of code (below), but the resulting view isn't centered -- the x-coordinate is always where a standard sized formsheet view would be. Changing the center property of the view and superview doesn't affect anything in a useful way. How can we use a custom formsheet size that is correctly centered?
Add the following code to the view controller that is being presented as a UIModalPresentationPageSheet:
#implementation MySpecialFormsheet {
CGRect _realBounds;
}
- (void)viewDidLoad {
// code below works great, but the resulting view isn't centered.
_realBounds = self.view.bounds;
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.view.superview.bounds = _realBounds;
}
I've only found success changing the frame after presenting it. I actually do it like so:
GameSetupViewController *gameSetup = [[GameSetupViewController alloc] init];
[gameSetup setDelegate:self];
[gameSetup setModalPresentationStyle:UIModalPresentationPageSheet];
[self presentModalViewController:gameSetup animated:YES];
[gameSetup.view.superview setAutoresizingMask:(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)];
[gameSetup.view.superview setFrame:CGRectMake(64, 64, 896, 640)];
But perhaps you could get away with using viewDidAppear or some other handle.

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