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

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.

Related

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

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.

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.

How to programmatically add a label in a custom subview?

I'm designing a card game (cards against humanity) for iOS, there are two types of cards, the whites ones, and the black ones. So I've implemented a CardView class which inherits from UIView, and two class, WhiteCardView and BlackCardView which both inherit from CardView.
As you guess, almost only the color will change between those two, but I still want two different view class for those two (even if they are almost the same at the moment). So, I have four questions about that.
EDIT: I mnage to find out some answer by myself, but for the last one, I'm lost.
1.I need advice on my implementation, I don't know if I'm doing it right to set the colors of the cards which is stored in CardView but set in the init of my WhiteCardView. I think I have to override only one init, but I don't know which one. So if someone can confirm or correct what I already did, that would be great. Thanks
Here is my CardView code:
IB_DESIGNABLE
#interface CardView : UIView
-(void)customDrawUI;
-(void)setData;
#property (nonatomic) UIColor* IBInspectable secondaryColor;
#property (nonatomic) UIColor* IBInspectable primaryColor;
#property(nonatomic) UILabel* txtLabel;
#end
#implementation CardView
-(void)customDrawUI{
self.layer.cornerRadius=5.0;
self.backgroundColor = self.primaryColor;
}
-(void)setData{
self.txtLabel.text = #"some text";
}
#end
And the WhiteCardView code:
IB_DESIGNABLE
#interface WhiteCardView : CardView
#end
#implementation WhiteCardView
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect myFrame = self.bounds;
CGContextSetLineWidth(context, 1);
CGRectInset(myFrame, 5, 5);
[self.secondaryColor set];
UIRectFrame(myFrame);
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
self.primaryColor= [UIColor whiteColor];
self.secondaryColor= [UIColor blackColor];
[super customDrawUI];
[super setData];
}
return self;
}
#end
2.In interface builder (where I correctly define the custom class for each of my cards), my views aren't live rendered, the code in my drawRect method WhiteCardView is executed but I can see no change.
And when I run my app, I get the same result. Just white rectangle, without any rounded angle.
Any idea why there is no changing in my view?
EDIT: I didn't put the IBDESIGNABLE tag in the right place, now it works !
3.Is there any way to execute that line: self.backgroundColor = self.primaryColor; in the parent drawRect method ? Because it's currently in both: White and BlackCardView, and there is certainly a way to do it in the parent class (I'll add common code to those two class, so I need a way to do it).
Maybe it's possible to do this in the init from CardView, but as it's not working at the moment, I can't test it.
EDIT: I find out, the setBackground couldn't be called from drawRect, so I define a new method in the CardView class to do that. And I call it from the init methods.
4.The most important part: how is it possible to add a label on each card (not via interface builder but via the CardView class), and be able to set its content programmatically?
I defined a property for that label, and I set its value but I have no idea how to render it.

Perfecting subview resizing in UICollectionView layout transition

I'm developing an app that has a UICollectionView - the collection view's job is to display data from a web service.
One feature of the app I am trying to implement is enabling the user to change the layout of this UICollectionView from a grid view to a table view.
I spent a lot of time trying to perfect this and I managed to get it to work. However there are some issues. The transition between the two layout doesn't look good and sometimes it breaks between switching views and my app is left with a view in an unexpected state. That only happens if the user switches between grid and table view very quickly (pressing the changeLayoutButton) continuously.
So, obviously there are some problems and I feel the code is a little fragile. I also need to fix the above mentioned issues.
I'll start off with how I implemented this view.
Implementation
Since I needed the two different cells (grideCell and tableViewCell) to show different things - I decided it would be better to subclass UICollectionViewFlowLayout since it does everything I need - all I need to do is change the cell sizes.
With that in mind I created two classes that subclassed UICollectionViewFlowLayout
This is how those two classes look:
BBTradeFeedTableViewLayout.m
#import "BBTradeFeedTableViewLayout.h"
#implementation BBTradeFeedTableViewLayout
-(id)init
{
self = [super init];
if (self){
self.itemSize = CGSizeMake(320, 80);
self.minimumLineSpacing = 0.1f;
}
return self;
}
#end
BBTradeFeedGridViewLayout.m
#import "BBTradeFeedGridViewLayout.h"
#implementation BBTradeFeedGridViewLayout
-(id)init
{
self = [super init];
if (self){
self.itemSize = CGSizeMake(159, 200);
self.minimumInteritemSpacing = 2;
self.minimumLineSpacing = 3;
}
return self;
}
#end
Very simple and as you can see - just changing the cell sizes.
Then in my viewControllerA class I implemented the UICollectionView like so:
Created the properties:
#property (strong, nonatomic) BBTradeFeedTableViewLayout *tableViewLayout;
#property (strong, nonatomic) BBTradeFeedGridViewLayout *grideLayout;
in viewDidLoad
/* Register the cells that need to be loaded for the layouts used */
[self.tradeFeedCollectionView registerNib:[UINib nibWithNibName:#"BBItemTableViewCell" bundle:nil] forCellWithReuseIdentifier:#"TableItemCell"];
[self.tradeFeedCollectionView registerNib:[UINib nibWithNibName:#"BBItemGridViewCell" bundle:nil] forCellWithReuseIdentifier:#"GridItemCell"];
The user taps a button to change between layouts:
-(void)changeViewLayoutButtonPressed
I use a BOOL to determine which layout is currently active and based on that I make the switch with this code:
[self.collectionView performBatchUpdates:^{
[self.collectionView.collectionViewLayout invalidateLayout];
[self.collectionView setCollectionViewLayout:self.grideLayout animated:YES];
} completion:^(BOOL finished) {
}];
In cellForItemAtIndexPath
I determine which cells I should use (grid or tableView) and the load the data - that code looks like this:
if (self.gridLayoutActive == NO){
self.switchToTableLayout = NO;
BBItemTableViewCell *tableItemCell = [collectionView dequeueReusableCellWithReuseIdentifier:tableCellIdentifier forIndexPath:indexPath];
if ([self.searchArray count] > 0){
self.switchToTableLayout = NO;
tableItemCell.gridView = NO;
tableItemCell.backgroundColor = [UIColor whiteColor];
tableItemCell.item = self.searchArray[indexPath.row];
}
return tableItemCell;
}else
{
BBItemTableViewCell *gridItemCell= [collectionView dequeueReusableCellWithReuseIdentifier:gridCellIdentifier forIndexPath:indexPath];
if ([self.searchArray count] > 0){
self.switchToTableLayout = YES;
gridItemCell.gridView = YES;
gridItemCell.backgroundColor = [UIColor whiteColor];
gridItemCell.item = self.searchArray[indexPath.row];
}
return gridItemCell;
}
Lastly in the two cell classes - I just use the data to set the image / text as I need.
Also in grid cell - the image is bigger and I remove text I don't want - which was the primary reason for uses two cells.
I'd be interested in how to make this view look a little more fluid and less buggy in the UI. The look I am going for is just like eBays iOS app - they switch between three different views. I just need to switch between two different views.
#jrturton's answer is helpful, however unless I'm missing something it is really overcomplicating something very simple. I'll start with the points we agree on...
Prevent interaction while changing layouts
First off, I agree with the approach of disabling user interaction at the start of the layout transition & reenabling at the end (in the completion block) using [[UIApplication sharedApplication] begin/endIgnoringInteractionEvents] - this is much better than trying cancel an in-progress transition animation & immediately begin the reverse transition from the current state.
Simplify the layout transition by using a single cell class
Also, I very much agree with the suggestion to use the same cell class for each layout. Register a single cell class in viewDidLoad, and simplify your collectionView:cellForItemAtIndexPath: method to just dequeue a cell and set its data:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
BBItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
if ([self.searchArray count] > 0) {
cell.backgroundColor = [UIColor whiteColor];
cell.item = self.searchArray[indexPath.row];
}
return cell;
}
(Notice that the cell itself shouldn't (in all but exceptional cases) need to be aware of anything to do with what layout is currently in use, whether layouts are transitioning, or what the current transition progress is)
Then when you call setCollectionViewLayout:animated:completion: the collection view doesn't need to reload any new cells, it just sets up an animation block to change each cell's layout attributes (you don't need to call this method from inside an performBatchUpdates: block, nor do you need to invalidate the layout manually).
Animating the cell subviews
However as pointed out, you will notice that subviews of the cell jump immediately to their new layout's frames. The solution is to simply force immediate layout of the cells subviews when the layout attributes are updated:
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
[super applyLayoutAttributes:layoutAttributes];
[self layoutIfNeeded];
}
(No need to create special layout attributes just for the transition)
Why does this work? When the collection view changes layouts, applyLayoutAttributes: is called for each cell as the collection view is setting up the animation block for that transition. But the layout of the cell's subviews is not done immediately - it is deferred to a later run loop - resulting in the actual subview layout changes not being incorporated into the animation block, so the subviews jump to their final positions immediately. Calling layoutIfNeeded means that we are telling the cell that we want the subview layout to happen immediately, so the layout is done within the animation block, and the subviews' frames are animated along with the cell itself.
It is true that using the standard setCollectionViewLayout:... API does restrict control of the animation timing. If you want to apply a custom easing animation curve then solutions like TLLayoutTransitioning demonstrate a handy way of taking advantage of interactive UICollectionViewTransitionLayout objects to take control of the animation timing. However, as long as only a linear animation of subviews is required I think most people will be satisfied with the default animation, especially given the one-line simplicity of implementing it.
For the record, I'm not keen on the lack of control of this animation myself, so implemented something similar to TLLayoutTransitioning. If this applies to you too, then please ignore my harsh reproval of #jrturton's otherwise great answer, and look into TLLayoutTransitioning or UICollectionViewTransitionLayouts implemented with timers :)
Grid / table transitions aren't as easy as a trivial demo would have you believe. They work fine when you've got a single label in the middle of the cell and a solid background, but once you have any real content in there, it falls over. This is why:
You have no control over the timing and nature of the animation.
While the frames of the cells in the layout are animated from one value to the next, the cells themselves (particularly if you are using two separate cells) don't seem to perform internal layout for each step of the animation so it seems to "flick" from one layout to the next inside each cell - your grid cell looks wrong in table size, or vice versa.
There are many different solutions. It's hard to recommend anything specific without seeing your cell's contents, but I've had success with the following:
take control of the animation using techniques like those shown here. You could also check out Facebook Pop to get better control over the transition but I haven't looked into that in any detail.
use the same cell for both layouts. Within layoutSubviews, calculate a transition distance from one layout to the other and use this to fade out or in unused elements, and to calculate nice transitional frames for your other elements. This prevents a jarring switch from one cell class to the other.
That's the approach I used here to fairly good effect.
It's harder work that relying on resizing masks or Autolayout but it's the extra work that makes things look good.
As for the issue when the user can toggle between the layouts too quickly - just disable the button when the transition starts, and re- enable it when you're done.
As a more practical example, here's a sample of the layout change (some of it is omitted) from the app linked above. Note that interaction is disabled while the transition occurs, I am using the transition layout from the project linked above, and there is a completion handler:
-(void)toggleLayout:(UIButton*)sender
{
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
HMNNewsLayout newLayoutType = self.layoutType == HMNNewsLayoutTable ? HMNNewsLayoutGrid : HMNNewsLayoutTable;
UICollectionViewLayout *newLayout = [HMNNewsCollectionViewController collectionViewLayoutForType:newLayoutType];
HMNTransitionLayout *transitionLayout = (HMNTransitionLayout *)[self.collectionView transitionToCollectionViewLayout:newLayout duration:0.5 easing:QuarticEaseInOut completion:^(BOOL completed, BOOL finish)
{
[[NSUserDefaults standardUserDefaults] setInteger:newLayoutType forKey:HMNNewsLayoutTypeKey];
self.layoutType = newLayoutType;
sender.selected = !sender.selected;
for (HMNNewsCell *cell in self.collectionView.visibleCells)
{
cell.layoutType = newLayoutType;
}
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}];
[transitionLayout setUpdateLayoutAttributes:^UICollectionViewLayoutAttributes *(UICollectionViewLayoutAttributes *layoutAttributes, UICollectionViewLayoutAttributes *fromAttributes, UICollectionViewLayoutAttributes *toAttributes, CGFloat progress)
{
HMNTransitionLayoutAttributes *attributes = (HMNTransitionLayoutAttributes *)layoutAttributes;
attributes.progress = progress;
attributes.destinationLayoutType = newLayoutType;
return attributes;
}];
}
Inside the cell, which is the same cell for either layout, I have an image view and a label container. The label container holds all the labels and lays them out internally using auto layout. There are constant frame variables for the image view and the label container in each layout.
The layout attributes from the transition layout are a custom subclass which include a transition progress property, set in the update layout attributes block above. This is passed into the cell using the applyLayoutAttributes method (some other code omitted):
-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
self.transitionProgress = 0;
if ([layoutAttributes isKindOfClass:[HMNTransitionLayoutAttributes class]])
{
HMNTransitionLayoutAttributes *attributes = (HMNTransitionLayoutAttributes *)layoutAttributes;
self.transitionProgress = attributes.progress;
}
[super applyLayoutAttributes:layoutAttributes];
}
layoutSubviews in the cell subclass does the hard work of interpolating between the two frames for the images and labels, if a transition is in progress:
-(void)layoutSubviews
{
[super layoutSubviews];
if (!self.transitionProgress)
{
switch (self.layoutType)
{
case HMNNewsLayoutTable:
self.imageView.frame = imageViewTableFrame;
self.labelContainer.frame = labelContainerTableFrame;
break;
case HMNNewsLayoutGrid:
self.imageView.frame = imageViewGridFrame;
self.labelContainer.frame = self.originalGridLabelFrame;
break;
}
}
else
{
CGRect fromImageFrame,toImageFrame,fromLabelFrame,toLabelFrame;
if (self.layoutType == HMNNewsLayoutTable)
{
fromImageFrame = imageViewTableFrame;
toImageFrame = imageViewGridFrame;
fromLabelFrame = labelContainerTableFrame;
toLabelFrame = self.originalGridLabelFrame;
}
else
{
fromImageFrame = imageViewGridFrame;
toImageFrame = imageViewTableFrame;
fromLabelFrame = self.originalGridLabelFrame;
toLabelFrame = labelContainerTableFrame;
}
CGFloat from = 1.0 - self.transitionProgress;
CGFloat to = self.transitionProgress;
self.imageView.frame = (CGRect)
{
.origin.x = from * fromImageFrame.origin.x + to * toImageFrame.origin.x,
.origin.y = from * fromImageFrame.origin.y + to * toImageFrame.origin.y,
.size.width = from * fromImageFrame.size.width + to * toImageFrame.size.width,
.size.height = from * fromImageFrame.size.height + to * toImageFrame.size.height
};
self.labelContainer.frame = (CGRect)
{
.origin.x = from * fromLabelFrame.origin.x + to * toLabelFrame.origin.x,
.origin.y = from * fromLabelFrame.origin.y + to * toLabelFrame.origin.y,
.size.width = from * fromLabelFrame.size.width + to * toLabelFrame.size.width,
.size.height = from * fromLabelFrame.size.height + to * toLabelFrame.size.height
};
}
self.headlineLabel.preferredMaxLayoutWidth = self.labelContainer.frame.size.width;
}
And that's about it. Basically you need a way of telling the cell how far through the transition it is, which you need the layout transitioning library (or, as I say, Facebook pop might do this) for, and then you need to make sure you get nice values for layout when transitioning between the two.

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