Reputation: 1021
So I am using PaintCode to make shapes, and I want my UIButton
to have that shape.
The shape I made looks like this in code:
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 81.5, y: 48.5))
bezierPath.addLineToPoint(CGPoint(x: 105.5, y: 24.5))
bezierPath.addLineToPoint(CGPoint(x: 129.5, y: 48.5))
bezierPath.addLineToPoint(CGPoint(x: 123.5, y: 48.5))
bezierPath.addLineToPoint(CGPoint(x: 105.5, y: 30.5))
bezierPath.addLineToPoint(CGPoint(x: 87.5, y: 48.5))
bezierPath.addLineToPoint(CGPoint(x: 81.5, y: 48.5))
bezierPath.closePath()
UIColor.whiteColor().setFill()
bezierPath.fill()
UIColor.blackColor().setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
And I set the UIButton
layers in my cellForItemAtIndexPath
, but how can I make the shape I made on my button?
Upvotes: 2
Views: 2636
Reputation: 1544
To do what you want to do, you have to create a new CocoaTouchClass which is a subclass of UIButton by right clicking and choosing "New File". Once you're in that file, you have to override a function called drawRect. This is what your file should look like-
import UIKit
class BezierButtonDrawing: UIButton {
override func drawRect (rect: CGRect) {
//your code from PaintCode goes here
}
}
All you have to do after that is, go to Main.storyboard, click on your button, and set it's class from the Identity Inspector to "BezierButtonDrawing" or whatever you have named your class.
If you have multiple shapes in your app, you can simply do what RichardG suggested. Here is the swift translation-
declare this in your class first (not in viewDidLoad)
var shapeLayer = CAShapeLayer()
Next, this is what you do in viewDidLoad
-
self.shapeLayer.lineWidth = 5.0
self.shapeLayer.fillColor = UIColor.blackColor().CGColor
self.shapeLayer.path = bezierPath.CGPath
self.shapeLayer.strokeColor = UIColor.blackColor().CGColor
self.yourButton.layer.addSublayer(shapeLayer)
That's it. Just build and run, and you'll have what you wanted :)
Upvotes: 1
Reputation: 8914
You can add path in layer. (here shapeLayer
declared as property.)
if (self.shapeLayer != nil) {
[self.shapeLayer removeFromSuperlayer];
self.shapeLayer = nil;
}
_shapeLayer = [CAShapeLayer layer];
self.shapeLayer.lineWidth = 5.0;
self.shapeLayer.fillColor = [UIColor clearColor].CGColor;
self.shapeLayer.path = bezierPath.CGPath;
self.shapeLayer.strokeColor = strokeColor.CGColor;
[[self.button layer] addSublayer:self.shapeLayer];
Upvotes: 0