I'm fairly new to UICollectionView. Though I've watched the WWDC talks on it I'm still unclear how to achieve my layout. I'm trying to constrain my flow layout to a square bottom aligned to the window's rootviewcontroller (see image). However, when setting UIEdgeInsetsMake(200, 10, 10, 10) which as I understand should compress only the top portion of the flow layout, instead what happens is the flow layout is compressed from top and bottom. Additionally, I'm not sure how to use -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect or -(CGSize)collectionViewContentSize to create this layout.
-(id)init
{
self = [super init];
if (self) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.itemSize = CGSizeMake(75, 75);
self.sectionInset = UIEdgeInsetsMake(100, 10, 10, 10);
}
return self;
}
What my results are:
What I'm trying to acheive:
I think the frame of collection view is different from what you need .Set it properly
Related
I have a problem.
Briefly: CGRectIntersectsRect(object1.frame, object2.frame) placed in UIViewController does not work for object1 and object2 created in different classes (Class1 and Class2). I only can change their coordinates like object1.center.x, and object1.frame.size.width = 0 (I guess this is why CGRectIntersection function does not work). These objects just came through each other.
As I understand it may be connected with protocol/delegating, but I haven't found any sufficient information how to be in my situation.
Platform.m (my class for creating a platform in the ViewController)
#implementation Platform
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
platformView = [[UIImageView alloc]initWithFrame:frame];
platformView.image = [UIImage imageNamed:#"platform.png"];
[self addSubview:platformView];
}
return self;
}
ViewController.m (in the #interface there are Platform *platform; Kelvin *kelvin;)
-(void)addPlatform
{
platform = [[Platform alloc]initWithFrame:CGRectMake(initialPlatformX, (500 - arc4random()%200), 200, 10)];
[self.view addSubview:platform];
}
**if (!CGRectIntersectsRect(kelvin.frame, platform.frame)) {
NSLog(#"%f", platform.frame.size.width);
}**
Your explanation is confusing and hard to follow.
This sentence, for example, is a total mystery to me:
As I understand it may be connected with protocol/delegating, but i
haven't found any sufficient information how to be in my situation.
Delegation? Huh? Rectangles are not objects. Delegation is a design pattern for objects. How is that relevant here? (Answer: Very likely it isn't relevant at all.)
Moving on, though, here are a few things to consider:
2 views' frames will only use the same coordinate system if they are both subviews of the same view. So are your platform and your "kelvin" view subviews of the same view (It looks like you add platform directly to the view controller's content view, so is your "kelvin" view also a subview of the view controller's content view?)
Also, you make reference to object1.frame.size.width = 0
The CGRectIntersectsRect function checks to see if any pixels of the 2 rectangles overlap. If either of your rectangles has either a height or a width of 0, it's empty, and can't intersect with anything.
In initWithFrame, you are adding a UIImageView subview to Platform using the frame of Platform. That is incorrect. For example, if you add PlatForm at CGRectMake(10, 10, 100, 100), you'll then be adding the image view at CGRectMake(10, 10, 100, 100) within Platform (which is CGRectMake(20, 20, 100, 100) within the original view).
So, instead, I think you want to make a CGRect that starts at 0, 0 (or use the bounds of Platform, not its frame):
#implementation Platform
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
platformView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
platformView.image = [UIImage imageNamed:#"platform.png"];
[self addSubview:platformView];
}
return self;
}
By the way, just to be safe, you might also want to set clipsToBounds to YES, so that if you ever change contentMode to something that doesn't scale to fit, you don't have to worry about the image bleeding over its bounds.
The best way to demonstrate my problem is with the video below:
http://foffer.dk/collectionview.mp4
As you can see, my collectionView doesn't update it's layout to correctly display the items until I start scrolling. I'm using a separate collectionViewFlowLayout model. Here is my code:
CollectionViewFlowLayout.m:
#implementation CollectionViewFlowLayout
- (void)prepareLayout {
CGFloat halfWidth = self.collectionView.bounds.size.width / 2;
CGFloat halfHeight = self.collectionView.bounds.size.height / 2;
self.itemSize = CGSizeMake(halfWidth, halfHeight);
self.minimumInteritemSpacing = 0;
self.minimumLineSpacing = 0;
}
// indicate that we want to redraw as we scroll
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
#end
my PhotosCollectionViewController (I've left out the standart collectionView stuff as I didn't think it is important to this issue, let me know if it is and I will post it):
-(instancetype)init {
UICollectionViewFlowLayout *layout = [[CollectionViewFlowLayout alloc] init];
return (self = [super initWithCollectionViewLayout:layout]);
}
-(void) viewDidLoad{
[super viewDidLoad];
[self.collectionView registerClass:[FOFPhotoCell class] forCellWithReuseIdentifier:#"photo"];
self.collectionView.backgroundColor = [UIColor whiteColor];
CGFloat bottomLayoutGuide = self.tabBarController.tabBar.frame.size.height;
self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, bottomLayoutGuide, 0);
}
-(BOOL)shouldAutorotate{
return YES;
}
Do I need to call invalidateLayout somewhere? I can't seem to figure out where to implement that method. [self.collectionView invalidateLayout] doesn't work.
Could someone get me on the right track here?
Thanks in advance
Chris
So, it turns out I had it set up all wrong. As this article from apple says:
Before you start building custom layouts, consider whether doing so is
really necessary.
The UICollectionViewFlowLayout class provides a
significant amount of behavior that has already been optimized for
efficiency and that can be adapted in several ways to achieve many
different types of standard layouts. The only times to consider
implementing a custom layout are in the following situations:
The layout you want looks nothing like a grid or a line-based breaking
layout (a layout in which items are placed into a row until it’s full,
then continue on to the next line until all items are placed) or
necessitates scrolling in more than one direction.
You want to change all of the cell positions frequently enough that it would be more work
to modify the existing flow layout than to create a custom layout.
And my layout config is really simple. So I was overcomplicating it.
I am using QuickDialog library in my IOS project. But it has a problem with table appearance:
The height of headerView in first table section is 10. But the top padding is much more than 10!
The table frame is right(fullscreen), and quickDialogTableView.contentInsets.top is also right(==64). But what the additional top space is? How to hack the library code to fix the problem?
Notice: it only happens when root.grouped == YES.
Try this:
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = self.quickDialogTableView.tableHeaderView.frame;
frame.size.height = 5;
UIView *headerView = [[UIView alloc] initWithFrame:frame];
self.quickDialogTableView.tableHeaderView = headerView;
}
Actually based on Sebastian answer this works, but is kind of hackie...
self.quickDialogTableView.tableHeaderView =
[UIView.alloc initWithFrame:CGRectMake(0, 0, 0, 0.1)];
In iOS 6 and earlier a uitableviewcell's imageView was positioned all the way over to the left with a 0 offset. In iOS 7 though this has been changed and there is now a 15 point space now. I would like to position the imageView like it is in iOS 6. I'm already subclassing the uitableviewcell with AKHighlightableAttributedCell to deal with attributed text not being highlighted. So based on some searching I added:
- (void) layoutSubviews
{
[super layoutSubviews];
// Makes imageView get placed in the corner
self.imageView.frame = CGRectMake( 0, 0, 80, 80 );
}
The issue is everything else still doesn't get repositioned and so I'm thinking there must be a better way to do this. I'd read some people mentioning using a negative offset to move everything over but I wasn't sure how this would work with constraints as it needs to scale properly for each orientation. Is there an easier solution to this that I'm missing? Thank you.
It appears I was doing it the correct way. The missing piece regarding the divider between fields was setting the inset on iOS 7. You can do this in the viewdidload or viewwillload and set self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
You will need to add a check if running iOS 7 or newer as this is a new property I believe. A better option might be setting it in the storyboard by selecting the table view and then setting separator insets from default to custom.
Here is the layoutSubviews method that repositions imageView and textLabel. If you have a description add that as well.
- (void) layoutSubviews
{
[super layoutSubviews];
// Makes imageView get placed in the corner
self.imageView.frame = CGRectMake( 0, 0, 80, 80 );
// Get textlabel frame
//self.textLabel.backgroundColor = [UIColor blackColor];
CGRect textlabelFrame = self.textLabel.frame;
// Figure out new width
textlabelFrame.size.width = textlabelFrame.size.width + textlabelFrame.origin.x - 90;
// Change origin to what we want
textlabelFrame.origin.x = 90;
// Assign the the new frame to textLabel
self.textLabel.frame = textlabelFrame;
}
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.