Skip to content

Instantly share code, notes, and snippets.

@MrAlek
Last active December 8, 2016 16:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrAlek/5e770e5cf546d5df0599 to your computer and use it in GitHub Desktop.
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
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