Skip to content

Commit

Permalink
Hide text field and text view cursors while snapshotting
Browse files Browse the repository at this point in the history
Resolves #15
  • Loading branch information
NickEntin committed Feb 17, 2024
1 parent a9c7312 commit d4c8b1d
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Example/SnapshotTests/DefaultControlsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,27 @@ final class DefaultControlsTests: SnapshotTestCase {
SnapshotVerifyAccessibility(container)
}

// MARK: - Text Input

func testTextFieldHidesCursor() {
let textField = UITextField()
textField.tintColor = .red
textField.isAccessibilityElement = false
textField.text = "Hello world"
textField.becomeFirstResponder()

let container = ContainerView(control: textField)
container.bounds.size = .init(width: 120, height: 44)

// This is testing flaky behavior, so run the test multiple times to ensure it's consistent.
for _ in 0..<10 {
SnapshotVerifyAccessibility(container)
}

// Ensure the tint color is restored.
XCTAssertEqual(textField.tintColor, .red)
}

}

// MARK: -
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ extension UIView {
) throws -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)

// Hide the cursor of text inputs to prevent test flakes.
var viewTintsToRestore: [UIView: UIColor] = [:]
recursiveForEach(viewType: UITextField.self) { inputView in
viewTintsToRestore[inputView] = inputView.tintColor
inputView.tintColor = .clear
}
recursiveForEach(viewType: UITextView.self) { inputView in
viewTintsToRestore[inputView] = inputView.tintColor
inputView.tintColor = .clear
}
defer {
viewTintsToRestore.forEach { inputView, tintColor in
inputView.tintColor = tintColor
}
}

var error: Error?

let snapshot = renderer.image { context in
Expand Down Expand Up @@ -191,4 +207,14 @@ extension UIView {

private static let tileSideLength: CGFloat = 2000

private func recursiveForEach<ViewType: UIView>(
viewType: ViewType.Type,
_ block: (ViewType) -> Void
) {
if let view = self as? ViewType {
block(view)
}
subviews.forEach { $0.recursiveForEach(viewType: viewType, block) }
}

}

0 comments on commit d4c8b1d

Please sign in to comment.