Last active
October 7, 2019 23:55
-
-
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.
This file contains hidden or 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
| // | |
| // 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