ASCollectionNode full-width layout for CellNode - ios

I want to make cells full-width in ASCollectionNode, but I'll get CellNodes sized by content.
I have implemented layoutSpecThatFits:.
See the image

My way to achieve that is adding extra node with full width inside ASStaticLayoutSpec.
In header:
#property (strong, nonatomic) ASDisplayNode *stretchNode;
In init
_stretchNode = [ASDisplayNode new];
[self addSubnode:_stretchNode];
layoutSpecThatFits:
- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize {
_stretchNode.sizeRange = ASRelativeSizeRangeMakeWithExactCGSize(CGSizeMake(constrainedSize.max.width, 0.5f));
NSArray *children = #[];
ASStackLayoutSpec *mainStackLayoutSpec = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:0 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsStart children:children];
ASStaticLayoutSpec *mainStaticLayoutSpec = [ASStaticLayoutSpec staticLayoutSpecWithChildren:#[mainInsetsLayoutSpec, _stretchNode]];
return mainStaticLayoutSpec;
}
Important part here is to wrap your layout and stretchNode in ASStaticLayoutSpec. You can replace StackLayout with anything you want.

Related

Why i can't move image and set text in label at the same time

I want to move background to the left like my character is walking and show number of walking but it can't do that at the same time. this method leftfootButton can only set text in label
- (IBAction)leftfootButton:(id)sender {
_bgGround.center = CGPointMake(_bgGround.center.x -50, _bgGround.center.y);
i = i+1;
self.show.text = [NSString stringWithFormat:#"%d",i];
}
If i comment the code that sets the text out then it can move background
- (IBAction)rightfootButton:(id)sender {
_bgGround.center = CGPointMake(_bgGround.center.x - 50, _bgGround.center.y);
i = i+1;
//self.show.text = [NSString stringWithFormat:#"%d",i];
}
what should i do?
You should not change frames directly when you use auto layout because layoutSubviews method will return frames to their previous position. This method is called by system in many cases. You could override it to set the frame rectangles of your subviews directly. But I recommend you to change constraints of your background view. Even if you did not set constraints to your views, they was added automatically.
When you use Layout Constraint then you should never change the frame, you should try to change the constraint, e.g.
Create a IBOutlet for x contraint for the view like below, make sure it's correctly connected.
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *xContraint;
Then in your action
- (IBAction)leftfootButton:(id)sender {
self.xContraint.constant -= 50;
i = i + 1;
self.show.text = [NSString stringWithFormat:#"%d", i];
}

How to make custom cell height effective?

Lately I have faced a problem with effeciency caused by heightForRowAtIndexPath:. Each time you have to draw cell you nerd to create it and calculate it size - it's so long!
One would say, why not use estimatedHeightForRowAtIndexPath: but when you pass estimation here you just loose accurancy so when you scroll to top some cells aren't visible at all...
I want to widen my knowledge in this matter. How do guys from Twitter, Facebook or Instagram did it?
I suppose you mean a situation when the height of a cell is determined by the content of the cell.
In general, the height of a cell in that case is calculated during layout process. There is no other way to calculate that height without performing layout at least once.
For example, you have a cell with a description label. You have a requirement to display the whole description as multiline text without truncating it. So, you have to make the description label of variable height.
When tableview asks you about cell’s height you have to calculate the number of lines required for the description text. This is exactly the same work you perform during layout of cell contents.
In a common case the layout process is a number of lightweight calculations. The idea is to extract that calculations code out of the cell class and access them directly as needed.
In the example below:
CellLayoutParams contains the initial information that should be taken into account when calculating layout. Here goes the data that should be shown by the cell and the cell width.
#interface CellLayoutParams : NSObject {
#property (nonatomic, copy) NSString* title;
#property (nonatomic, copy) NSString* description;
#property (nonatomic, assign) CGFloat width;
- (BOOL)isEqualToLayoutParams:(CellLayoutParams*)params;
#end
CellStyle is an object that describes the style attributes of the cell. E.g. the font of the description label, various cell paddings, margins and insets.
#interface CellStyle : NSObject
#property(nonatomic, strong) UIFont* titleFont;
#property(nonatomic, strong) UIFont* descriptionFont;
- (struct CellLayoutInfo)layoutInfoForParams:(CellLayoutParams*)params;
#end
#implementation CellStyle
- (struct CellLayoutInfo)layoutInfoForParams:(CellLayoutParams*)params {
CellLayoutInfo layoutInfo;
const CGPoint contentOffset = CGPointMake(kLeftMargin, kTopMargin);
const CGFloat contentWidth = params.width - kAccessoryWidth - kLeftMargin;
NSString* descriptionValue = params.description;
CGSize descriptionSize = [descriptionValue sizeWithFont: [self descriptionFont]
constrainedToSize: CGSizeMake(contentWidth, CGFLOAT_MAX)];
layoutInfo.descriptionFrame.size = descriptionSize;
layoutInfo.descriptionFrame.origin = CGPointMake(contentOffset.x, layoutInfo.titleFrame.origin.y + layoutInfo.titleFrame.size.height + kVerticalInset);
layoutInfo.preferredHeight = layoutInfo.descriptionFrame.origin.y + descriptionSize.height + kBottomMargin;
return layoutInfo
}
#end
CellLayoutInfo is a structure with calculated layout information: calculated frames and preferred height value.
typedef struct CellLayoutInfo {
CGRect titleFrame;
CGRect descriptionFrame;
CGFloat preferredHeight;
} CellLayoutInfo;
You just need to perform layout calculations to get the preferred height:
- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath*)indexPath {
MyData* dataItem = [self.data objectAtIndex:indexPath.row];
CellLayoutParams* layoutParams = [CellLayoutParams new];
layoutParams.description = dataItem.description;
layoutParams.width = table.bounds.size.width;
CellStyle* cellStyle = [CellStyle new];
CellLayoutInfo layoutInfo = [cellStyle layoutInfoForParams:layoutParams];
return layoutInfo.preferredHeight;
}
In cell's layoutSubviews you access the same calculated layout values:
- (void) layoutSubviews {
[super layoutSubviews];
CellLayoutParams* layoutParams = [CellLayoutParams new];
layoutParams.description = self.descriptionLabel.text;
layoutParams.width = self.bounds.size.width;
CellStyle* cellStyle = [CellStyle new];
CellLayoutInfo layoutInfo = [cellStyle layoutInfoForParams:layoutParams];
self.titleLabel.frame = layoutInfo.titleFrame;
self.descriptionLabel.frame = layoutInfo.descriptionFrame;
}
Few things to note:
You don't need to create multiple style objects. The style object is immutable and is the same for all cells.
The code of layout is not duplicated. The table view delegate and the cell are using the same layouting code.
You may perform few additional optimizations:
Cache CellLayoutInfo objects in the controller and reuse them. This is useful when there is much scrolling through the table.
Keep a copy of CellLayoutInfo and corresponding CellLayoutParams in the cell and when the cell is being reused just check if params where changed and if a new CellLayoutInfo should be calculated. This is useful when the table view is being reloaded frequently.
The only drawback is that you have to define all the styling and layout in the code.

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.

Hide dynamically created UILabels in IBAction

I have declared UILabel in ViewController first like this:
#property (weak, nonatomic) IBOutlet UILabel *answerLabel;
Then I have created label in a loop:
//creating answer labels
i = 0;
int y=200;
while (i < numberOfAnswers) {
UILabel *answerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, 300, 20)];
answerLabel.text = [NSString stringWithFormat:#"%# (%#)", questionBank[randomQuestionNumber][1][i][0],questionBank[randomQuestionNumber][1][i][1]];
answerLabel.hidden=NO;
[self.view addSubview:answerLabel];
i++;
y = y + 20;
}
In the IBAction I have this but it doesn't work. Any ideas where the mistakes is?
- (IBAction)nextQuestion:(id)sender {
//hiding labels
self.answerLabel.hidden=YES;
}
I would suggest first create view and then add those labels in this view.
Now when you need to hide, just hide this view.
Hope this answer.
For what you are doing, it is lengthy way. First white creating label you have to set tag. Then for hiding, again get label by tag and then hide accordingly.
Your code contains lots of issues.
First of all, when you are talking about multiple outlets, in the declaration it should be outletCollection like this:
#property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *answerLabels;
Again, as you are creating your labels dynamically, you just can't add them in your IBOuletCollection.
#FahimParkar is suggesting a good approach. But as you might need to work with individual labels, you might use following approach..
First declare an array of labels like this:
#property (strong, nonatomic) NSMutableArray *answerLabels;
Now when you are creating the label, alloc your array & add new labels in it like this:
i = 0;
int y=200;
self.answerLabels= [[NSMutableArray alloc]init]
while (i < numberOfAnswers) {
UILabel *answerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, 300, 20)];
answerLabel.text = [NSString stringWithFormat:#"%# (%#)", questionBank[randomQuestionNumber][1][i][0],questionBank[randomQuestionNumber][1][i][1]];
answerLabel.hidden=NO;
[self.view addSubview:answerLabel];
[self.answerLabels addObject:answerLabel]
i++;
y = y + 20;
}
Now when you want to hide a particular label, you can do this by referring anyone of these three:
Array index.
labelText.
add tag for your label as suggested by Fahim & refer to it.. :)
Let me know if more info needed.. :)

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