Last active
December 8, 2016 16:55
-
-
Save MrAlek/5e770e5cf546d5df0599 to your computer and use it in GitHub Desktop.
A simple, @IBDesignable view which draws a pixel wide hairline of chosen color in chosen direction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
import QuartzCore | |
enum HairlineDirection: Int { | |
case Left, Right, Top, Bottom, None | |
init(point: CGPoint) { | |
if point.x < 0 { | |
self = Left | |
} else if point.x > 0 { | |
self = Right | |
} else if point.y > 0 { | |
self = Top | |
} else if point.y < 0 { | |
self = Bottom | |
} else { | |
self = None | |
} | |
} | |
} | |
@IBDesignable | |
class HairlineView: UIView { | |
@lazy var hairlineLayer: CALayer = { | |
return CALayer() | |
}() | |
@IBInspectable var hairlineColor: UIColor = UIColor.blackColor() { | |
didSet { hairlineLayer.backgroundColor = hairlineColor.CGColor } | |
} | |
@IBInspectable var direction: CGPoint = CGPointZero { | |
didSet { setNeedsLayout() } | |
} | |
let Thickness = 1.0/UIScreen.mainScreen().scale | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
if hairlineLayer.superlayer != layer { | |
layer.addSublayer(hairlineLayer) | |
} | |
var hairlineFrame = CGRectZero | |
let hairlineDirection = HairlineDirection(point: direction) | |
switch hairlineDirection { | |
case .Left: | |
hairlineFrame = CGRect(x: 0, y: 0, width: Thickness, height: bounds.height) | |
case .Right: | |
hairlineFrame = CGRect(x: bounds.width-Thickness, y: 0, width: Thickness, height: bounds.height) | |
case .Top: | |
hairlineFrame = CGRect(x: 0, y: 0, width: bounds.width, height: Thickness) | |
case .Bottom: | |
hairlineFrame = CGRect(x: 0, y: bounds.height-Thickness, width: bounds.width, height: Thickness) | |
default: | |
hairlineFrame = CGRectZero | |
} | |
hairlineLayer.frame = hairlineFrame | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment