Skip to content

Instantly share code, notes, and snippets.

@rynecheow
Created October 7, 2014 07:04
Show Gist options
  • Save rynecheow/b9296b35f0869a18e571 to your computer and use it in GitHub Desktop.
Save rynecheow/b9296b35f0869a18e571 to your computer and use it in GitHub Desktop.
//
// PolygonalView.swift
// Freebie
//
// Created by Ryne Cheow on 10/5/14.
// Copyright (c) 2014 Ryne Cheow. All rights reserved.
//
import UIKit
@IBDesignable
public class PolygonalView: UIView {
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
// Initialization code
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override public func prepareForInterfaceBuilder() {
setup()
}
@IBInspectable public var sides: Int = 9 {
didSet {
updateUI()
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
updateUI()
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
updateUI()
}
}
@IBInspectable public var cornerRadius: CGFloat = 5 {
didSet {
updateUI()
}
}
private func setup(){
let path = UIBezierPath.roundedPolygonPathWithRect(self.bounds, lineWidth: borderWidth, sides: sides, cornerRadius: cornerRadius)
let maskLayer = CAShapeLayer()
maskLayer.path = path.CGPath
maskLayer.lineWidth = borderWidth;
maskLayer.strokeColor = UIColor.clearColor().CGColor
maskLayer.fillColor = UIColor.whiteColor().CGColor
self.layer.mask = maskLayer
let borderLayer = CAShapeLayer()
borderLayer.path = path.CGPath
borderLayer.lineWidth = borderWidth
borderLayer.strokeColor = borderColor.CGColor
borderLayer.fillColor = UIColor.clearColor().CGColor
self.layer.addSublayer(borderLayer)
}
private func updateUI(){
for layer in self.layer.sublayers as [CALayer] {
layer.removeFromSuperlayer()
}
setup()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment