iOS 6.0: UICollectionView doesn't respect clipsToBounds with pagingEnabled - objective-c

Background
I am implementing a UICollectionView (for the first time) in an effort to achieve a paged horizontal scroll view of tiles. I'd like each tile to show in the center of the frame with it's sister tiles partially visible to the left and right (something like the page selector in the Safari app). I'm interested in using the UICollectionView to take advantage of built-in cell dequeueing and would rather not use a rotated UITableView.
Issue
The issue I'm finding is that when using pagingEnabled = YES and clipsToBounds = NO, the UICollectionView removes cells outside the collectionView frame (they're not in the visibleCells array) as soon as paging is complete. Can anyone provide advice on how to achieve the effect of displaying previews of the sister tiles while maintaining this basic setup? Or am I approaching this incorrectly?
Screenshots
start
scrolling
end
The scrolling screen is exactly correct. But in the start and end shots I want there to be green visible in the blue margins.
Here's what's in my AppDelegate.m (credit to tutsplus.com for the basic setup here):
#import "AppDelegate.h"
#interface ViewController : UICollectionViewController
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"ID"];
[self.view setBackgroundColor:[UIColor blueColor]];
// pad the collection view by 20 px
UIEdgeInsets padding = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0);
[self.collectionView setFrame:UIEdgeInsetsInsetRect(self.view.frame, padding)];
// set pagingEnabled and clipsToBounds off
[self.collectionView setPagingEnabled:YES];
[self.collectionView setClipsToBounds:NO];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 5;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ID" forIndexPath:indexPath];
UILabel *label = [[UILabel alloc] initWithFrame:cell.bounds];
label.textAlignment = NSTextAlignmentCenter;
label.text = [NSString stringWithFormat:#"%d", indexPath.row];
[label setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:label];
return cell;
}
#end
#implementation AppDelegate
{
ViewController *vc;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// setup the UICollectionViewFlowLayout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(280, 280);
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0;
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// add a custom UICollectionViewController to the window
vc = [[ViewController alloc] initWithCollectionViewLayout:layout];
self.window.rootViewController = vc;
self.window.backgroundColor = [UIColor yellowColor];
[self.window makeKeyAndVisible];
return YES;
}
#end

Turns out the solution to this was actually quite simple. I just needed to overlap the UICollectionViewCell cells by enough pixels to have them still show within the collectionView's frame after the paged scrolling finishes. The relevent code was
layout.itemSize = CGSizeMake(300, 300);
layout.minimumLineSpacing = -20.0;
And I subclassed the UICollectionViewFlowLayout and overrode the (CGSize)collectionViewContentSize method to return the non-overlapped size of the cells.

Many thanks for the tip about using a negative minimumLineSpacing. I created a tester application which uses a collection view cell loaded from a xib file. The cell has a transparent background and an “inner” view for the cell's content.
In this way, a custom flow layout is not necessary.
https://github.com/j4johnfox/CollectionViewTester

I'm not an expert in collectionView, but it could be possibly do with this line in cellForItemAtIndexPath:
[cell.contentView addSubview:label];
Everytime it's called, another label subview is added to cell. Either check for an existing label or subclass UICollectionViewCell?

You'll want to also override -pointInside:withEvent: to allow scroll gestures to start outside the frame of the collection view. I do this using a UIEdgeInsets property in my collection view subclass:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect extendedBounds = UIEdgeInsetsInsetRect(self.bounds, self.touchAreaInsets);
return CGRectContainsPoint(extendedBounds, point);
}
If you don't need App Store safety, you can override _visibleBounds to avoid negative spacing hacks:
- (CGRect)_visibleBounds {
return UIEdgeInsetsInsetRect(self.bounds, self.touchAreaInsets);
}
If you're not too pressed on code size and need App Store safety you could also subclass PSTCollectionView and possibly override visibleBoundRects for the same effect.

Related

UITableViewCell drawInRect iOS7

Hi I am trying to draw strings in my UITableViewCell in iOS 7 with the following code
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
CGRect playerNameRect = CGRectMake(0, kCellY, kPlayerNameSpace, kCellHeight);
NSDictionary*dictonary = [NSDictionary
dictionaryWithObjectsAndKeys:
[UIColor hmDarkGreyColor], NSForegroundColorAttributeName,
kFont, NSFontAttributeName,
nil];
[self.playerName drawInRect:playerNameRect withAttributes:dictonary];
}
However I can not get anything to appear... self.playerName is not nil, and the playerNameRect is correct.
I was previously using the following code to do the same thing but was recently deprecated in iOS 7
[self.playerName drawInRect:playerNameRect withFont:kFont lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentCenter];
What is also strange is I can not get anything to draw in drawRect on a UITableViewCell... The deprecated code works when I am drawingRect on just a UIView.
You shouldn't use UITableViewCell's drawRect method to perform custom drawing. The proper way to do it is to create a custom UIView and add it as a subview of your cell (as a subview of the contentView property). You can add the drawing code to this custom view and everything will work fine.
Hope this helps!
Check out these posts too:
Table View Cell custom drawing 1
Table View Cell custom drawing 2
Table View Cell custom drawing 3
As others said, don't use UITableViewCell's drawRect selector directly. By doing that, you're relying on implementation details of UITableViewCell, and Apple made no guarantee that such behaviour won't break in future versions, just as it did in iOS 7... Instead, create a custom UIView subclass, and add it as a subview to the UITableViewCell's contentView, like this:
#implementation CustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self.contentView addSubview:[[CustomContentView alloc]initWithFrame:self.contentView.bounds]];
}
return self;
}
#end
And the CustomContentView:
#implementation CustomContentView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSDictionary * attributes = #{
NSFontAttributeName : [UIFont fontWithName:#"Helvetica-bold" size:12],
NSForegroundColorAttributeName : [UIColor blackColor]
};
[#"I <3 iOS 7" drawInRect:rect withAttributes:attributes];
}
#end
Works like charm!
Try setting cell.backgroundColor = [UIColor clearColor] in init.
While I agree with the accepted answer, here's my take on it for the records:
If you don't need any of the builtin UITableViewCell functionality (swiping, removing, reordering, ...) and just use it as a container to draw your custom stuff, then you might want to consider removing all of the cells subviews in tableview:willDisplayCell:ForRowAtIndexPath. This will make your drawing be visible again and will get you maximum performance (since you get rid of the subviews you don't need).

UITextView not becoming first responder

I have a UIView that contains a UITextView. The UIView is initiated inside a UIViewController.
But when I touch the UITextView box, nothing happens. Neither the keyboard appears nor delegate methods respond to interaction.
Code:
noteText = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 700, 240)];
noteText.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
noteText.layer.borderWidth = 2;
[noteText setEditable:YES];
noteText.userInteractionEnabled = YES;
noteText.returnKeyType = UIReturnKeyDone;
noteText.font = [UIFont fontWithName:#"Calibri" size:16];
noteText.textColor = [UIColor blackColor];
[self addSubview:noteText];
Update 1
I removed all other views from the UIViewController, and only put a UITextView in the UIViewController and still not reacting. Neither cursor or keyboard appear.
noteText = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 700, 240)];
noteText.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
noteText.layer.borderWidth = 2;
[noteText setEditable:YES];
noteText.userInteractionEnabled = YES;
noteText.returnKeyType = UIReturnKeyDone;
noteText.font = [UIFont fontWithName:#"Calibri" size:16];
noteText.textColor = [UIColor blackColor];
[self addSubview:noteText];
// Two suggestions
self.userInteractionEnabled = YES; // superview may blocks touches
self.clipsToBounds = YES; // superview may clips your textfield, you will see it
I found the error.
In one class I categorize the UITextView instead of subclass and set canBecomeFirstResponder to NO.
try this:
in your .h file conform the delegate UITextViewDelegate
:<UITextViewDelegate>
in your .m file:
noteText.delegate = self;
And delegate methods:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
[textView becomeFirstResponder];
return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
//resign for exapmple
return YES;
}
Hope this help!
I know it's late, but maybe for someone it'll be helpful. I had the same problem, and it disappeared after I used
[self setSelectable:true];
in my UITextView subclass.
Check this things:
add your viewcontroller on the right UIWindow.
set window makeKeyAndVisible and add rootViewController to window at this method:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
I think here is something wrong in xib file or at appdelegate.
Try overriding - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { inside the UIView to see if it's receiving touches
Just in case, try setting userInteractionEnabled = YES; for your UIView object. If it's somehow set as NO it will trickle down to all of its subviews
Maybe you have some mistake in your overriden -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event method? Maybe you do resignFirstResponder there or put some view above all?
Whenever something like this happens check the following items,
Make sure that the Text view is properly retained and released only in dealloc.(If you are not using ARC)
Check the frame of both Text view and it's parent views. Make sure that the subview is fitting exactly inside the parent view. Also make sure that this is the case with all the superviews of text view.
Check whether the delegate is set properly.
If all these are done, try adding a button on top of text view and check if it's target selector is getting called. If yes, the issue is with text view delegate or release statement. Otherwise the issue is with frame setting of Text view or it's superviews.

Different transparencies in Cocoa?

I have overloaded NSWindow and have created a custom window of my own (Borderless and transparency of 0.3 alphaValue). I am going to be drawing images in this window. Is there any way I can get the images that will be drawn in the window opaque? I want the window to remain transparent but want the images to be opaque. How would I do this?
Mac OS X Snow Leopard
Xcode 3.2.6
#ughoavgfhw is on the right track, but it's actually much easier. You just need to set opaque to NO and set backgroundColor to semi-transparent.
#implementation MYWindow
- (void)setup
{
[self setStyleMask:NSBorderlessWindowMask];
[self setOpaque:NO];
[self setBackgroundColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.3]];
}
// We override init and awakeFromNib so this works with or without a nib file
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
self = [super initWithContentRect:contentRect styleMask:aStyle backing:bufferingType defer:flag];
if (self)
{
[self setup];
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self setup];
}
#end
There's a potential problem with this approach.
Requesting "[self setStyleMask:NSBorderlessWindowMask];" (with any of the possible StyleMask values) will cause the loss of keystroke events to that window on subsequent presentations of the window as a sheet. I reported a bug to Apple today on this point.
Leave the alphaValue property to 1, and set the opaque property to NO. Then, replace the default contentView with one which fills itself with a color whose alpha component is 0.3 in its drawRect: method. When you change the alphaValue property, it changes how everything drawn in the window is displayed. When you make it non-opaque, it simply doesn't draw a black background beneath the content view, so if the content view is transparent, the window will be too, but anything drawn on top of that will not be affected.
Here's an example which uses a white background with a 0.3 alpha component. Note that I overrode the setContentView: method. This is so that I can copy any views from the passed view into the transparent content view, and is especially necessary if you load the window from a nib, since the nib loading will change the content view when it is loaded. (You could change the content view's class in IB instead.)
#interface MyWindow_ContentView : NSView
#end
#implementation MyWindow
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag {
if(self = [super initWithContentRect:contentRect styleMask:aStyle backing:bufferingType defer:flag]) {
[super setOpaque:NO];
[super setContentView:[[[MyWindow_ContentView alloc] init] autorelease]];
}
return self;
}
- (void)setOpaque:(BOOL)ignored {}
- (void)setContentView:(NSView *)newView {
NSArray *views = [[self.contentView subviews] copy];
[views makeObjectsPerformSelector:#selector(removeFromSuperview)];
views = [[newView subviews] copy];
[views makeObjectsPerformSelector:#selector(removeFromSuperview)];
for(NSView *view in views) [self.contentView addSubview:view];
[views release];
}
#end
#implementation MyWindow_ContentView
- (void)drawRect:(NSRect)rect {
[[NSColor colorWithCalibratedWhite:1 alpha:0.3] set];
NSRectFill(rect);
}
#end

UITableView Overlay when section index touched

I have a very custom table view that actually serves as a content view, but table view was the obvious choice. I have a section index that i use to scroll the TableView - but there are no sections (well, one is there obviously). For the purpose of the user's orientation, I'd like to fade a view over the table view that is semi-transparent and shows a text in there. It should look like the overlay with the letters when scrolling the new iPod nano's section index. I don't know where i should put the code - because my view has to disappear sometime again too, and I don't really wanna use notifications. I'd init the view inside the tableview: sectionForSectionIndexTitle method. Thanks in advance.
Create a property in your .h file
#property (nonatomic, retain) UILabel *overlayLabel;
And add the following code to your .m file
- (void)viewDidLoad {
[super viewDidLoad];
self.overlayLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f,
0.0f,
self.tableView.frame.size.width,
self.tableView.frame.size.height)] autorelease];
overlayLabel.backgroundColor = [UIColor clearColor];
overlayLabel.alpha = .5f;
overlayLabel.textAlignment = UITextAlignmentCenter;
overlayLabel.text = #"Some text";
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.tableView addSubview:overlayLabel];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[overlayLabel removeFromSuperview];
}

ModalViewController for Single Subview

Ok, so bear with me: as this is an Objective-C related question, there's obviously a lot of code and subclassing. So here's my issue. Right now, I've got an iPad app that programmatically creates a button and two colored UIViews. These colored UIViews are controlled by SubViewControllers, and the entire thing is in a UIView controlled by a MainViewController. (i.e. MainViewController = [UIButton, SubViewController, SubViewController])
Now, all of this happens as it should, and I end up with what I expect (below):
However, when I click the button, and the console shows "flipSubView1", nothing happens. No modal view gets shown, and no errors occur. Just nothing. What I expect is that either subView1 or the entire view will flip horizontally and show subView3. Is there some code that I'm missing that would cause that to happen / is there some bug that I'm overlooking?
viewtoolsAppDelegate.m
#implementation viewtoolsAppDelegate
#synthesize window = _window;
#synthesize mvc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mvc = [[MainViewController alloc] initWithFrame:self.window.frame];
[self.window addSubview:mvc.theView];
[self.window makeKeyAndVisible];
return YES;
}
MainViewController.m
#implementation MainViewController
#synthesize theView;
#synthesize subView1, subView2, subView3;
- (id)initWithFrame:(CGRect) frame
{
theView = [[UIView alloc] initWithFrame:frame];
CGRect sV1Rect = CGRectMake(frame.origin.x+44, frame.origin.y, frame.size.width-44, frame.size.height/2);
CGRect sV2Rect = CGRectMake(frame.origin.x+44, frame.origin.y+frame.size.height/2, frame.size.width-44, frame.size.height/2);
subView1 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor blueColor]];
subView2 = [[SubViewController alloc] initWithFrame:sV2Rect andColor:[UIColor greenColor]];
subView3 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor redColor]];
[theView addSubview:subView1.theView];
[theView addSubview:subView2.theView];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton addTarget:self action:#selector(flipSubView1:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
[aButton setFrame:CGRectMake(0, 0, 44, frame.size.height)];
[theView addSubview:aButton];
return self;
}
- (void)flipSubView1:(id) sender
{
NSLog(#"flipSubView1");
[subView3 setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[subView1 presentModalViewController:subView3 animated:YES];
}
SubViewController.m
#implementation SubViewController
#synthesize theView;
- (id)initWithFrame:(CGRect)frame andColor:(UIColor *)color
{
theView = [[UIView alloc] initWithFrame:frame];
theView.backgroundColor = color;
return self;
}
TLDR: modal view not working. should see flip. don't.
It doesn't look like you're setting the 'view' property of the MainViewController anywhere, just 'theView'. The controllers view delegate must be connected to the root view it displays for it to work properly. You'll need to correct that on the Sub View Controller impl as well. If you want all the plumbing that framework classes bring, you have to set things up the way they expect.
Also, you're calling presentModalViewController on one of the sub view controllers; change that to call [self presentModalViewController:...], since the MainViewController is the one which will 'own' the modal view.
I think if you fix those points, you'll find -presentModalViewController will work.