Transforming UICollectionViewCell causes touch events not be captured - ios

Im trying to create a horizontal collection view by subclassing UICollectionViewFlowLayout.
which the center cell be scaled a little more to be focused on the view.
see the screen shot:
but UICollectionViewCell doesn't capture touch events. I mean when I tap on the cell the delegate method - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath won't called.
but when I remove the scale transform from the cell, the above method called!
#import "CoverFlowLayout.h"
static const CGFloat kMaxDistancePercentage = 0.3f;
static const CGFloat kMaxRotation = (CGFloat)(50.0 * (M_PI / 180.0));
static const CGFloat kMaxZoom = 0.1f;
#implementation CoverFlowLayout
- (id)init {
if ((self = [super init])) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.minimumLineSpacing = 10000.0f; }
return self;
}
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
// 1
CGRect visibleRect =
(CGRect){.origin = self.collectionView.contentOffset,
.size = self.collectionView.bounds.size};
CGFloat maxDistance =
visibleRect.size.width * kMaxDistancePercentage;
// 2
NSArray *array =
[super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attributes in array) {
// 3
CGFloat distance =
CGRectGetMidX(visibleRect) - attributes.center.x;
// 4
CGFloat normalizedDistance = distance / maxDistance;
normalizedDistance = MIN(normalizedDistance, 1.0f);
normalizedDistance = MAX(normalizedDistance, -1.0f);
// 5
CGFloat rotation = normalizedDistance * kMaxRotation;
CGFloat zoom = 1.0f + ((1.0f - ABS(normalizedDistance)) * kMaxZoom);
// 6
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -1000.0;
//transform = CATransform3DRotate(transform,
// rotation, 0.0f, 1.0f, 0.0f);
transform = CATransform3DScale(transform, zoom, zoom, 0.0f);
attributes.transform3D = transform;
}
// 7
return array;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
- (CGPoint)targetContentOffsetForProposedContentOffset: (CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
// 1
CGFloat offsetAdjustment = CGFLOAT_MAX;
CGFloat horizontalCenter = proposedContentOffset.x +
(CGRectGetWidth(self.collectionView.bounds) / 2.0f);
// 2
CGRect targetRect = CGRectMake(proposedContentOffset.x,
0.0f, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray *array =
[super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes* layoutAttributes in array)
{
// 3
CGFloat distanceFromCenter = layoutAttributes.center.x - horizontalCenter;
if (ABS(distanceFromCenter) < ABS(offsetAdjustment))
{
offsetAdjustment = distanceFromCenter;
}
}
// 4
return CGPointMake(proposedContentOffset.x + offsetAdjustment,
proposedContentOffset.y);
}
any idea?

You don't need to scale on z-axis, the problem is caused because you were scaling on z to zero
The scale on z-axis should be greater than zero; Making it zero causes the button to have "no depth", so the touches are not recognized. (Although you can still see the button)
Scaling is a computed using a multiplication, so in order to cause "no transformation on z-axis", the value should be 1, rather than 0

I had to scale the cell along the Z axis too:
transform = CATransform3DScale(transform, zoom, zoom, zoom);
the cell touch events works.
does anyone knows why scaling along Z axis is necessary?

Related

Animated custom layout in UICollectionView

I need to create a UICollectionView like the following picture.
I have been able to make horizontally scrollable, but unable to make the UI like the picture. Any help? Thanks.
Here is what you wanted,you just need to have a custom UICollectionViewFlowLayout,and override the method -(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect to change the cell display attributes.
Here is the layout code with comment in each main operation
#implementation HorizonSclaeLayout
-(instancetype)init{
self = [super init];
if (self) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}
return self;
}
static const CGFloat kMaxDistancePercentage = 0.3f;
static const CGFloat kMaxRotation = 0;//(CGFloat)(70.0 * (M_PI / 180.0));
static const CGFloat kMaxZoom = 0.6f;
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//1 the visible rectangle of the collection view, calculated using the content offset of the view and the bounds size.
CGRect visibleRect = (CGRect){
.origin = self.collectionView.contentOffset,
.size = self.collectionView.bounds.size
};
//2 the maximum distance away from the center, which defines the distance from the center at which each cell is fully rotated
CGFloat maxDistance = visibleRect.size.width/2;
NSArray *array = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attributes in array) {
//3 find the distance of the cell from the center of the current visible rectangle
CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;
//4 normalize this distance against the maximum distance to give a percentage of how far the view is along the line from the center to the maximum points in either direction
CGFloat normalizedDistance = distance / maxDistance;
normalizedDistance = MIN(normalizedDistance, 1.0f);
normalizedDistance = MAX(normalizedDistance, -1.0f);
//5 calculate the rotation and zoom
CGFloat rotation = normalizedDistance * kMaxRotation;
CGFloat zoom = 1.0f + ((1.0f - ABS(normalizedDistance))*kMaxZoom);
//6 create the required transform by first setting m34 so that when the rotation is done
// skew is applied to make it have the appearance of coming out of and going into the screen
CATransform3D transform = CATransform3DIdentity;
transform.m34 = - 1.0 / 550.0;
transform = CATransform3DRotate(transform, rotation, 0.0f, 1.0f, 0.0f);
transform = CATransform3DScale(transform, zoom, zoom, 0.0f);
attributes.transform3D = transform;
}
return array;
}
-(CGSize)itemSize{
return CGSizeMake(60, 60 * 1.2);
}
-(CGFloat)minimumLineSpacing{
return 30;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
#end
Here in this sample LineLayout has already implemented the required custom layout (that's what I guessed from the image shown).

How to zoom from min to max coordinates positions in UIScrollView?

I have a UIScrollView, which hold an UIImageView. I have a requirements to reach and zoom to particular location in UIImageView.
So for e.g. I want to start from (x: 0, y: 0) to specified location.
What's the best practice to do that?
This is how I'm achieving this:
- (void) setInitialZoomLevelAndShowImageInCenter {
CGRect scrollViewFrame = scrollViewMap.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / scrollViewMap.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / scrollViewMap.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
scrollViewMap.minimumZoomScale = minScale/1.5;
scrollViewMap.maximumZoomScale = 10.0f;
scrollViewMap.zoomScale = minScale;
CGFloat newZoomScale = scrollViewMap.zoomScale * 2.80f;
CGFloat xPos = 0;
CGFloat yPos = 0;
BOOL isMatched = NO;
while (!isMatched) {
[self zoomToPoint:CGPointMake(xPos, yPos) withScale:newZoomScale animated:YES];
BOOL isAnyChange = NO;
if(xPos <= slotItem.xCord) {
xPos+=1.0f;
isAnyChange = YES;
}
if(yPos <= slotItem.yCord) {
yPos+=1.0f;
isAnyChange = YES;
}
if(!isAnyChange) {
isMatched = YES;
}
}
}
- (void)zoomToPoint:(CGPoint)zoomPoint withScale: (CGFloat)scale animated: (BOOL)animated
{
//Normalize current content size back to content scale of 1.0f
CGSize contentSize;
contentSize.width = (scrollViewMap.contentSize.width / scrollViewMap.zoomScale);
contentSize.height = (scrollViewMap.contentSize.height / scrollViewMap.zoomScale);
//derive the size of the region to zoom to
CGSize zoomSize;
zoomSize.width = scrollViewMap.bounds.size.width / scale;
zoomSize.height = scrollViewMap.bounds.size.height / scale;
//offset the zoom rect so the actual zoom point is in the middle of the rectangle
CGRect zoomRect;
zoomRect.origin.x = zoomPoint.x - zoomSize.width / 2.0f;
zoomRect.origin.y = zoomPoint.y - zoomSize.height / 2.0f;
zoomRect.size.width = zoomSize.width;
zoomRect.size.height = zoomSize.height;
//apply the resize
[scrollViewMap zoomToRect: zoomRect animated: animated];
}

UICollectionViewCell disappears in iOS 8

I have a collectionView which works well in iOS 7 and now in iOS 8 is acts strangely.
when collectionView appears it only displays one cell: (it must be 2)
but after scrolling a bit the second cell appears
Im using a custom collectionViewFlowLayout. but changing to UICollectionViewFlowLayout doesn't fix the issue.
Cell Size : 657, 500
Min Spacing For Lines : 100
Min Spacing For Cells : 10
I have added left and right edge insets: (if I remove the insets it works well. but I must use insets to keep my cell at the center of view)
- (UIEdgeInsets)collectionView:(UICollectionView *)cv
layout:(UICollectionViewLayout *)cvl
insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0, (cv.bounds.size.width - 657) / 2.0f, 0,
(cv.bounds.size.width - 657) / 2.0f);
}
Here is my custom flow layout:
#import "CoverFlowLayout.h"
static const CGFloat kMaxDistancePercentage = 0.3f;
//static const CGFloat kMaxRotation = (CGFloat)(50.0 * (M_PI / 180.0));
static const CGFloat kMaxZoom = 0.1f;
#implementation CoverFlowLayout
- (id)init {
if ((self = [super init])) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.minimumLineSpacing = 10000.0f; }
return self;
}
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
// 1
CGRect visibleRect =
(CGRect){.origin = self.collectionView.contentOffset,
.size = self.collectionView.bounds.size};
CGFloat maxDistance =
visibleRect.size.width * kMaxDistancePercentage;
// 2
NSArray *array = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attributes in array) {
// 3
CGFloat distance =
CGRectGetMidX(visibleRect) - attributes.center.x;
// 4
CGFloat normalizedDistance = distance / maxDistance;
normalizedDistance = MIN(normalizedDistance, 1.0f);
normalizedDistance = MAX(normalizedDistance, -1.0f);
// 5
//CGFloat rotation = normalizedDistance * kMaxRotation;
CGFloat zoom = 1.0f + ((1.0f - ABS(normalizedDistance)) * kMaxZoom);
// 6
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -1000.0;
//transform = CATransform3DRotate(transform,
// rotation, 0.0f, 1.0f, 0.0f);
transform = CATransform3DScale(transform, zoom, zoom, zoom);
attributes.transform3D = transform;
}
// 7
return array;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
- (CGPoint)targetContentOffsetForProposedContentOffset: (CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
// 1
CGFloat offsetAdjustment = CGFLOAT_MAX;
CGFloat horizontalCenter = proposedContentOffset.x +
(CGRectGetWidth(self.collectionView.bounds) / 2.0f);
// 2
CGRect targetRect = CGRectMake(proposedContentOffset.x,
0.0f, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray *array =
[super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes* layoutAttributes in array)
{
// 3
CGFloat distanceFromCenter = layoutAttributes.center.x - horizontalCenter;
if (ABS(distanceFromCenter) < ABS(offsetAdjustment))
{
offsetAdjustment = distanceFromCenter;
}
}
// 4
return CGPointMake(proposedContentOffset.x + offsetAdjustment,
proposedContentOffset.y);
}
initially in overrided layoutAttributesForElementsInRect visible rect is {0,0, 1024, 768}
but [super layoutAttributesForElementsInRect:rect]; returns only one UICollectionViewCellAttribute. (it should be 2)
is any idea how can I fix this?
I don know How it can be cause of the issue but it was originated from:
NSIndexPath *visibleIndexPath = [self.collectionView indexPathForItemAtPoint:midPoint];
I want to update my pageControl to indicate which cell is at the center of screen.
I Changed my method and now it works well:
//*****updating page control*****
// get the visible rect
CGRect visibleRect = (CGRect) {.origin = self.collectionView.contentOffset,
.size = self.collectionView.bounds.size};
// get the mid point in the visible rect
CGPoint midPoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
// find indexPath of the item in that midPoint
//in iOS 8 Cause the second cell disappear
//NSIndexPath *visibleIndexPath = [self.collectionView indexPathForItemAtPoint:midPoint];
//iterating through visble cells to find the cell which contains midpoint then get get that cell indexpath
for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
if (CGRectContainsPoint(cell.frame, midPoint)) {
NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//update page control
self.pageControl.currentPage = indexPath.row;
//quiting loop
break;
}
}

Why isn't my curved text centering itself?

I have a UIView subclass called dpCurvedLabel. It uses CATextLayers to curved text around an arc. It works fine, except that I can't get it perfectly centered in the layers parent view. I want the center point for the arc to be at the very center of the view (even if the view is smaller) so all the text characters are the same distance from the center.
I can get it CLOSE but it's always a at least few pixels off. The amount it's 'off' seems to be effected by the frame size I give each CATextLayer. There's something wrong with the math, but I can't figure out what. My code:
// instantiate a dpCurvedLabel in a super view
dpCurvedLabel *curvedLabel = [[dpCurvedLabel alloc]
initWithFrame:CGRectMake(0, 0, 200, 200) arcSize:360 radius:50
text:#"curve curve curve " font:[UIFont fontWithName:#"HelveticaNeue" size:18]
textColor:[UIColor whiteColor]];
// You can animate a rotation to see a more pronounced effect
// [curvedLabel rotateContinously];
[self addSubview:curvedLabel];
dpCurvedLabel.h
#import <UIKit/UIKit.h>
#interface dpCurvedLabel : UIView
#property CGFloat arcSize;
#property CGFloat radius;
#property (strong) NSString *text;
#property (strong) UIFont *font;
#property (strong) UIColor *textColor;
- (id)initWithFrame:(CGRect)frame arcSize:(CGFloat)arcSize radius:(CGFloat)radius
text:(NSString *)text font:(UIFont *)font
textColor:(UIColor *)textColor;
- (void)rotateContinously;
+ (void)makeCurvedText:(CALayer *)layer arcSize:(CGFloat)arcSize radius:(CGFloat)radius
text:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor;
#end
dpCurvedLabel.m
#import "dpCurvedLabel.h"
#implementation dpCurvedLabel
- (id)initWithFrame:(CGRect)frame arcSize:(CGFloat)arcSize radius:(CGFloat)radius text:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.opaque = NO;
self.clipsToBounds = NO;
self.arcSize = arcSize;
self.radius = radius;
self.text = text;
self.font = font;
self.textColor = textColor;
}
return self;
}
- (void)layoutSublayersOfLayer:(CALayer *)layer
{
[super layoutSublayersOfLayer:layer];
NSLog(#"laying out sublayers!");
[dpCurvedLabel makeCurvedText:layer arcSize:self.arcSize radius:self.radius text:self.text font:self.font textColor:self.textColor];
}
+ (void)makeCurvedText:(CALayer *)layer arcSize:(CGFloat)arcSize radius:(CGFloat)radius text:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor
{
layer.sublayers = nil;
layer.masksToBounds = NO;
CGFloat arcStart = 0;
CGFloat shiftH = 0;
CGFloat shiftV = 0;
BOOL clockwise = YES;
BOOL debugMode = YES;
CGFloat xcenter = CGRectGetMidX(layer.bounds);
CGFloat ycenter = CGRectGetMidY(layer.bounds);
CGFloat angle = arcStart;
CGFloat angleStep = arcSize / text.length;
for ( NSUInteger i = 0; i < text.length; ++i )
{
NSRange range = { .location = i, .length = 1 };
NSString *c = [text substringWithRange:range];
CGFloat yoffset = sin( degreesToRadians(angle) ) * radius;
CGFloat xoffset = cos( degreesToRadians(angle) ) * radius;
CGFloat rotAngle = 90 - angle;
if ( clockwise )
{
yoffset = -yoffset;
rotAngle = -90 + angle;
}
CATextLayer* tl = [[CATextLayer alloc] init];
tl.masksToBounds = NO;
tl.wrapped = NO;
tl.truncationMode = kCATruncationNone;
if ( debugMode )
{
tl.borderWidth = 1;
tl.cornerRadius = 3;
tl.borderColor = [UIColor whiteColor].CGColor;
}
// Text layer frame determined here. Effects how arc is centered.
CGSize charSize = CGSizeMake(20, 20);
tl.frame = CGRectMake( shiftH + xcenter - xoffset, shiftV + ycenter + yoffset, charSize.width, charSize.height );
// *******
tl.font = (__bridge CFTypeRef)(font.fontName);
tl.fontSize = font.pointSize;
tl.foregroundColor = textColor.CGColor;
tl.string = c;
tl.alignmentMode = #"center";
tl.transform = CATransform3DMakeAffineTransform( CGAffineTransformMakeRotation( degreesToRadians(rotAngle) ) );
[layer addSublayer:tl];
angle += angleStep;
}
if ( debugMode )
{
layer.backgroundColor = RGBA(0x00, 0x00, 0x00, .6).CGColor;
}
}
- (void)rotateContinously
{
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * 1 * 1 ];
rotationAnimation.duration = 5;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = INT_MAX;
[self.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}
#end
What's wrong with the math here? Why won't this text arc center itself?
The problem comes from the fact that you are setting the frame of each text layer instead of its position. This means that you are positioning the lower left corner to be at the location where the position should be. Do this instead:
tl.position = CGPointMake( shiftH + xcenter - xoffset, shiftV + ycenter + yoffset);
tl.bounds = CGRectMake(0,0,charSize.width,charSize.height);
And you will find your layers to be exactly where you want them.

Path 2.0 menu animation xcode

I've downloaded Menu Path 2.0 from https://github.com/yourabi/PathMenuExample/downloads.
The "Add" button make expanding & collapsing an array of menu items (animated menu drawn along a curve).
But I want to make those button expanding/collapsing in a straight line.
Here is code
ExpandableNavigation.m:
- (void) expand {
transition = YES;
[UIView animateWithDuration:self.speed animations:^{
self.mainButton.transform = CGAffineTransformMakeRotation( 45.0 * M_PI/180 );
}];
for (UIView* view in self.menuItems) {
int index = [self.menuItems indexOfObject:view];
CGFloat oneOverCount = self.menuItems.count + 50<=1?1.0:(1.0/(self.menuItems.count-1));
CGFloat indexOverCount = index *oneOverCount;
CGFloat rad =(1.0 - indexOverCount) * 90.0 * M_PI/180;
CGAffineTransform rotation = CGAffineTransformMakeRotation( rad ) ;
CGFloat x = (self.radius + self.bounce * self.radius ) * rotation.a;
CGFloat y = (self.radius + self.bounce * self.radius ) * rotation.c;
CGPoint center = CGPointMake( view.center.x + x , view.center.y + y);
For anyone needs in future, change the angle with your desired angle of transformation.
- (void) expand {
transition = YES;
[UIView animateWithDuration:self.speed animations:^{
self.mainButton.transform = CGAffineTransformMakeRotation( 45.0 * M_PI/180 );
}];
for (UIView* view in self.menuItems) {
int index = [self.menuItems indexOfObject:view];
CGFloat oneOverCount = self.menuItems.count + 50<=1?1.0:(1.0/(self.menuItems.count-1));
CGFloat indexOverCount = index *oneOverCount;
CGFloat rad =(1.0 - indexOverCount) * 90.0 * M_PI/180;
CGAffineTransform rotation = CGAffineTransformMakeRotation( rad ) ;
CGFloat x = yourDesired_X; //should be same for all menu items
CGFloat y = (view.frame.size.hieght+8.0)*index; //Y should be increasing or decreasing for every item
CGPoint center = CGPointMake(x , y);

Resources