Skip to content

Instantly share code, notes, and snippets.

@aydenp
Last active October 7, 2019 23:55
Show Gist options
  • Select an option

  • Save aydenp/365875c8d96d30a08867f4198b882ebe to your computer and use it in GitHub Desktop.

Select an option

Save aydenp/365875c8d96d30a08867f4198b882ebe to your computer and use it in GitHub Desktop.
Create a view equal to exactly one real pixel in height, even on Retina and Retina HD displays.
//
// HairlineView.swift
//
// Created by Ayden Panhuyzen on 2018-04-02.
// Copyright © 2018 Ayden Panhuyzen. All rights reserved.
// https://gist.github.com/aydenp
//
import UIKit
class HairlineView: UIView {
private var constraint: NSLayoutConstraint?
convenience init(axis: NSLayoutConstraint.Axis) {
self.init(frame: .zero)
defer { self.axis = axis }
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
translatesAutoresizingMaskIntoConstraints = false
constraint?.isActive = false
constraint = (axis == .horizontal ? heightAnchor : widthAnchor).constraint(equalToConstant: desiredSize)
constraint!.isActive = true
}
override func didMoveToWindow() {
super.didMoveToWindow()
constraint?.constant = desiredSize
}
var axis: NSLayoutConstraint.Axis = .horizontal {
didSet { setup() }
}
private var desiredSize: CGFloat {
return 1 / (window?.screen.scale ?? 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment