Skip to content

Instantly share code, notes, and snippets.

@shaps80
Last active July 31, 2018 21:01
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 shaps80/03dee451c0dd26548ee5bef281f9c653 to your computer and use it in GitHub Desktop.
Save shaps80/03dee451c0dd26548ee5bef281f9c653 to your computer and use it in GitHub Desktop.
Adds right-to-left support to UIEdgeInsets
#if canImport(AppKit)
import AppKit
public typealias EdgeInsets = NSEdgeInsets
public typealias UserInterfaceLayoutDirection = NSUserInterfaceLayoutDirection
#endif
#if canImport(UIKit)
import UIKit
public typealias EdgeInsets = UIEdgeInsets
public typealias UserInterfaceLayoutDirection = UIUserInterfaceLayoutDirection
#endif
public extension EdgeInsets {
init(top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat, interfaceDirection: UserInterfaceLayoutDirection? = nil) {
let direction = interfaceDirection ?? UIApplication.shared.userInterfaceLayoutDirection
switch direction {
case .leftToRight:
self.init(top: top, left: leading, bottom: bottom, right: trailing)
case .rightToLeft:
self.init(top: top, left: trailing, bottom: bottom, right: leading)
}
}
}
import Quick
import Nimble
override func spec() {
describe("When using convenience initializers") {
it("should have equal insets for all edges") {
let inset = UIEdgeInsets(all: 4)
expect(inset.top).to(equal(4))
expect(inset.bottom).to(equal(4))
expect(inset.left).to(equal(4))
expect(inset.right).to(equal(4))
}
it("should have equal insets for top and bottom") {
let inset = UIEdgeInsets(horizontal: 4, vertical: 0)
expect(inset.left).to(equal(4))
expect(inset.right).to(equal(4))
}
it("should have equal insets for left and right") {
let inset = UIEdgeInsets(horizontal: 0, vertical: 4)
expect(inset.top).to(equal(4))
expect(inset.bottom).to(equal(4))
}
}
describe("When using leading/trailing convenience") {
context("and the language is currently left-to-right") {
it("left should equal leading and right should equal trailing") {
let insets = UIEdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 8)
expect(insets.left).to(equal(4))
expect(insets.right).to(equal(8))
}
}
context("and the language is currently right-to-left") {
it("left should equal trailing and right should equal leading") {
let insets = UIEdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 8, interfaceDirection: .rightToLeft)
expect(insets.left).to(equal(8))
expect(insets.right).to(equal(4))
}
}
}
}
@PSchu
Copy link

PSchu commented Jul 25, 2018

I think there is a small Typo

#if canImport(AppKit)
import UIKit

shouldn't it be

#if canImport(AppKit)
import AppKit

@shaps80
Copy link
Author

shaps80 commented Jul 31, 2018

Thanks @PSchu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment