CATransformLayer touch events handling - ios

I have searched over the internet and Stackoverflow but i couldn't find any answer to this specific question, So here's my question,
I'm trying to create a double sided UIView which responds to touch events both sides(Such as UIButton, UISwitch, etc...). I have achieved that by adding two distinct CALayers to CATransformLayer. All works good but touches doesn't responds to the ui elements added from interface builder. To replicate the problem, i have created an UIView in the nib(frontView) added all ui elements from interface builder and add that UIView reference to CATransformLayer and all works good except it doesn't respond to touch events.
I understand that CALayer or CATransformLayer doesn't inherits from UIResponder class like UIView. And i believe there is a way to bring this layer to responder chain but i'm wondering how?. Below is my simplified problem code,
- (void)viewDidLoad
{
[super viewDidLoad];
CATransformLayer *myLayer = [[CATransformLayer alloc] initWithLayer:self.view.layer];
myLayer.frame = CGRectMake(0, 0, 300, 300);
[myLayer addSublayer:frontView.layer];//Here 'frontView' is a reference to UIView from nib file
[self.view.layer addSublayer:myLayer];
}
Any support will greatly appreciate.
Thanks in advance.

Related

Create round UIButton with custom drawRect: method

My goal is to create a custom UIButton subclass, that creates a round (or round rect) button with some additional features.
After some searching, I found that simply setting the cornerRadius of the button layer is the easiest way to make the button round:
#implementation MyRoundButton
-(id)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame])
[self setupView];
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super initWithCoder:aDecoder])
[self setupView];
return self;
}
-(void)setupView {
self.layer.cornerRadius = MIN(self.frame.size.height, self.frame.size.width) / 2.0;
}
This works fine to, as long as I do not override drawRect:
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
}
Of course I would like to add some custom drawing code to drawRect: but even if only [super drawRect:rect] the button is not round anymore: It drawn as rectangle within its bounds.
How is this possible? How can overriding a method with a simple super call change the behavior at all?
How can I avoid this problem? I already tried to let the layer unchanged and to simply draw the background manually in drawRect:. However the button draws its background rect anyway and my custom drawing is on top of it.
So, how to solve this?
The layer in your example conceptually contains a background with a corner radius, but the empty override of drawRect: causes that to be ignored. That's because, ordinarily, an instance of UIView depends on its built-in layer (an instance of CALayer) to render its content, so drawRect: isn't called. However, the layer is capable of delegating drawing behavior to its view, and will do so if you implement drawRect:.
If you're simply subclassing UIView, this shouldn't present any problem. However, subclassing a framework component such as UIButton is a bit dicier. One potential issue is the call to -[super drawRect:]; it's hard to know precisely what mischief that might cause, but that may be the source of the problem. By default, a UIButton doesn't need to do any custom drawing; it contains a nested instance of a private class, UIButtonLabel, that draws the button's title.
Instead of trying to override the drawing behavior of a class whose inner details are private, consider using one or more static images and simply setting the button's background image property for one or more states.
See if this changes anything...
-(void)setupView {
self.layer.cornerRadius = MIN(self.frame.size.height, self.frame.size.width) / 2.0;
self.clipsToBounds = YES;
}

SpriteKit and Scrollable List

I've been trying to figure out an "easy" way to have a scrollable vertical list for my SpriteKit game.
I'm going to use it to implement the shop / upgrades part of my game so I would like the user to be able to scroll down the list to see the different upgrades that are possible.
I've seen quite a few posts on integrating a UIScrollView into SpriteKit but most of them seem to scroll the whole screen.
What I have so far is:
-(void) createSceneContents
{
[super createSceneContents];
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10,100, 250, 200)];
_scrollView.contentSize = CGSizeMake(2000, 120);
_scrollView.scrollEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = YES;
_scrollView.backgroundColor = [UIColor brownColor];
[self.view addSubview:_scrollView];
//Test sprites for scrolling and zooming
SKSpriteNode *greenTestSprite = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor]
size:CGSizeMake(25, 25)];
[greenTestSprite setName:#"greenTestSprite"];
greenTestSprite.position = CGPointMake(25, 125);
[self addChild:greenTestSprite];
//[self addChild: [self newMenuNode]];
}
I'm trying to think what the easiest way is for me to be able to add the green test sprite into that UIScrollView. can't get my head round the way that other people have done this as they seem to be connecting the scrolling of the UIScrollView with the SKView to make the screen seem like it's scrolling.
I'm sure there is a much easier way of doing this but been searching for a while now.
Any help would be appreciated.
Thanks allot in advance.
I would avoid using UIKit components if possible. When you have a UIView that is parented to UIKit components, it makes it difficult to interact with your SpriteKit components that live in the SKView. It's pretty easy to subclass SKNode and make a "ScrollingNode" that uses gesture recognizers on the SKView to do the scrolling. Here's an example:
https://github.com/JenDobson/SpriteKitScrollingNode
Another great tutorial to take a look at is http://www.raywenderlich.com/44270/sprite-kit-tutorial-how-to-drag-and-drop-sprites. Go to the part at the end on gesture recognizers.
You can use UIKit in a SpriteKit application.
If you use a UIScrollView you are going to end up having to get your hands dirty regarding re-use of cells, layout, user-interaction etc. You can actually make a cell look pretty good (and a cell is a UIView so you can sack a bunch of subviews in there) if you just use (and customise) a UITableView
Your hierarchy would be:
Scene:
TableView

iOS Custom UIView Drawing - CAShapeLayers or drawRect?

I'm new to iOS UIView drawing and I'm really trying to implement a custom UIView class in a standard way.
The UIView class that I'm working on now is simple: it has mostly static background shapes that form a composite shape. I also want to add animation to this UIView class so that a simple shape can animate its path on top of the static shapes.
How I'm currently implementing this
Right now, I'm implementing the static drawing in the drawRect: method of the UIView subclass. This works fine. I also have not implemented animation of the single shape yet.
What I'm looking to have answered
Question 1:
Is it better to have the static shapes drawn in the drawRect: method as I'm currently doing it, or is there a benefit to refactoring all of the shapes being drawn into class-extension-scoped CAShapeLayer properties and doing something like:
-(instancetype) initWithFrame:(CGRect) frame
{
if (self = [super initWithFrame:frame])
{
[self setupView];
}
return self;
}
-(void) setupView // Allocate, init, and setup one-time layer properties like fill colorse.
{
self.shapeLayer1 = [CAShapeLayer layer];
[self.layer addSubLayer:shapeLayer1];
self.shapeLayer2 = [CAShapeLayer layer];
[self.layer addSubLayer:shapeLayer2];
// ... and so on
}
-(void) layoutSubviews // Set frames and paths of shape layers here.
{
self.shapeLayer1.frame = self.bounds;
self.shapeLayer2.frame = self.bounds;
self.shapeLayer1.path = [UIBezierPath somePath].CGPath;
self.shapeLayer2.path = [UIBezierPath somePath].CGPath;
}
Question 2:
Regardless of whether I implement the static shapes as CAShapeLayers or in drawRect:, is the best way to implement an animatable shape for this UIView a CAShapeLayer property that is implemented as the other CAShapeLayers would be implemented above? Creating a whole separate UIView class just for one animated shape and adding it as a subview to this view seems silly, so I'm thinking that a CAShapeLayer is the way to go to accomplish that.
I would appreciate any help with this very much!
You could do it either way, but using shape layers for everything would probably be cleaner and faster. Shape layers have built-in animation support using Core Animation.
It's typically faster to avoid implementing drawRect and instead let the system draw for you.
Edit:
I would actually word this more strongly than I did in 2014. The underlying drawing engine in iOS is optimized for tiled rendering using layers. You will get better performance and smoother animation by using CALayers and CAAnimation (or higher level UIView or SwiftUI animation which is built on CAAnimation.)

Custom border for UIView using CALayer and autolayout

I have to draw a custom border for a UIView.
I already have code to do that but it was written before we started using autolayout.
The code basically adds a sublayer of width/height=1.0f
-(void)BordeIzquierdo:(UIColor *)pcColor cfloatTamanio:(CGFloat )pcfloatTamanio
{
CALayer* clElemento = [self layer];
CALayer *clDerecho = [CALayer layer];
clDerecho.borderColor = [UIColor darkGrayColor].CGColor;
clDerecho.borderWidth = pcfloatTamanio;
clDerecho.frame = CGRectMake(0, 1, pcfloatTamanio, self.frame.size.height);
[clDerecho setBorderColor:pcColor.CGColor];
[clElemento addSublayer:clDerecho];
}
Now the problem is that with autolayout, this happens before layoutSubViews. So UIView.layer.frame is (0,0;0,0) and so the sublayer added is not shown because it has width/height=0.0f
Now how can I make this code without transferring this custom drawing to another method executed after viewDidLoad such as didLayoutSubviews.
I would like this styling to be correctly applied before viewDidLoad is called.
Is there anything like autolayout constraints that I can use with CALayers?
Any other ideas?
There is no CALayer autoresizing or constraints in iOS. (There is on Mac OS X, but no in iOS.)
Your requirements here are unreasonable. You say that you refuse to move the call to BordeIzquierdo:. But you can't give clDerecho a correct size until you know the size of self (and therefore self.layer). Half the art of Cocoa touch programming is putting your code in the right place. You must find the right place to put the call to BordeIzquierdo: so that the values you need have meaning at the moment it is called.
What I would do is put it in layoutSubviews along with a BOOL flag so that you only do it once.

iOS: How to catch a tap event on a marker on a map that has a CALayer on top of it?

I have a mapView (RouteMe mapView) on which there are annotations (markers).
On the mapView there is a touchesEnded function on which I usually catch all events.
Some markers have an added layer on top of them.
That layer has some animation images and as much as I know this is the only way I can show these animation images on top of the markers.
The problem is that I don't know how I can intercept a touch on a marker that has that layer on top of it. When I test the hit on the touchesEnded I recognize a CALayer class rather than a RMMArker class (obv0iously, because the layer is on top of the marker, therefore is first to intercept the event).
How can I reach the Marker once the top CALayer is tapped?
Thanks
Hackish workaround: Create an RMMapLayer instead of a CALayer. Remember to set the annotation on the sublayer to get things like callouts to work, e.g. in your RMMapLayer subclass:
RMMapLayer *sublayer = [[RMMapLayer alloc] init];
sublayer.annotation = ann;
sublayer.contents = (id)img2.CGImage;
sublayer.contentsScale = img2.scale;
sublayer.position = CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
sublayer.bounds = CGRectMake(0, 0, img2.size.width, img2.size.height);
[self addSublayer:sublayer];
I don't know how many other things this has potential for breaking though, so you can follow this issue for any updates:
https://github.com/mapbox/mapbox-ios-sdk/issues/190
You can instruct the touches to passthrough. Take a look at this question: How can I click a button behind a transparent UIView?
Since the CALayer was on top of a CALAyer, all it took was to access it ancestor blockingLayer.superlayer.
By checking on the ancestor, I could have all that I needed.
This solved the problem.

Resources