Search code examples
iosobjective-cskspritenodeskshapenode

iOS Subclassing SKShapeNode


How does one go about subclassing an SKShapeNode that has no instance method initializers? The only way I could think of was this:

+ (id)withColor:(UIColor *)aColor radius:(CGFloat)aRadius {
    return [[self alloc] initWithColor:aColor radius: aRadius];
}

- (id)initWithColor:(UIColor *)aColor radius:(CGFloat)aRadius {
    self = (CAButtonNode *)[SKShapeNode shapeNodeWithCircleOfRadius:aRadius];
    self.fillColor = aColor;
    self.strokeColor = [UIColor clearColor];

    return self;
}

In which case self is an instance of SKShapeNode rather than CAButtonNode.

Thanks.


Solution

  • You can add a class extension to SKShapeNode

    extension SKShapeNode
    {
        class func nodeWithColor( color:UIColor, radius:Float ) -> Self
        {
            let node = SKShapeNode()
            node.path = CGPathCreateWithEllipseInRect(...)
            node.fillColor = ...
            node.strokeColor = ...
    
            return node
        }
    }
    

    Use like this:

    let newNode = SKShapeNode.nodeWithColor( theColor, radius: theRadius )

    Or, in Obj-C:

    @implementation SKShapeNode (NodeWithColorAndRadius)
    
    +(instancetype)nodeWithColor:(UIColor*)color radius:(CGFloat)r
    {
        SKShapeNode * result = [ self new ] ;
        result.path = ...;
        result.fillColor = ...;
        result.strokeColor = ...;
    }
    
    @end
    

    Call like this:

    [ SKShapeNode nodeWithColor:theColor radius:theRadius ]