Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created October 27, 2020 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjstelling/4d168ed1a2347a909b3fd13f6a9bb23f to your computer and use it in GitHub Desktop.
Save rjstelling/4d168ed1a2347a909b3fd13f6a9bb23f to your computer and use it in GitHub Desktop.
Accessibility Border Button
import UIKit
class BorderButton: UIButton {
private class BorderLayer: CAShapeLayer {
fileprivate var _borderWidth: CGFloat { UIAccessibility.isBoldTextEnabled ? 2.0 : 1.0 }
fileprivate var _cornerRadius: CGFloat = 4.0
override var lineWidth: CGFloat { get { _borderWidth } set { } }
override var fillColor: CGColor? { get { UIColor.clear.cgColor } set { } }
override var path: CGPath? { get { super.path } set { } }
fileprivate func updateBorder() {
let rect = CGRect(origin: .zero, size: self.frame.size).insetBy(dx: _borderWidth, dy: _borderWidth)
super.path = UIBezierPath(roundedRect: rect, cornerRadius: _cornerRadius).cgPath
}
}
override class var layerClass: AnyClass { BorderLayer.self }
private var borderLayer: BorderLayer? { self.layer as? BorderLayer }
// This is called regardless of how the AXButton is created, IB or code
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.titleLabel?.adjustsFontForContentSizeCategory = true
self.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body)
}
override func layoutSubviews() {
super.layoutSubviews()
// Disable CALayer's implicit animations while changing layer properties.
CATransaction.setDisableActions(true)
// Make its color match the view's tintColor.
// Since we are inside `layoutSubviews()`, UIKit has already set `UITraitCollection.current`
// to be the view's `traitCollection`. Calling `cgColor` will resolve the dynamic tint color,
// using that trait collection, to a static `CGColor`.
// When the traits change, UIKit ensures it calls `layoutSubviews` again.
self.borderLayer?.strokeColor = self.tintColor.cgColor
self.borderLayer?.updateBorder()
CATransaction.setDisableActions(false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment