Skip to content

Commit 89af04a

Browse files
committed
Hide text field and text view cursors while snapshotting
Resolves #15
1 parent 047fd17 commit 89af04a

File tree

6 files changed

+47
-0
lines changed

6 files changed

+47
-0
lines changed

Example/SnapshotTests/DefaultControlsTests.swift

+21
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,27 @@ final class DefaultControlsTests: SnapshotTestCase {
101101
SnapshotVerifyAccessibility(container)
102102
}
103103

104+
// MARK: - Text Input
105+
106+
func testTextFieldHidesCursor() {
107+
let textField = UITextField()
108+
textField.tintColor = .red
109+
textField.isAccessibilityElement = false
110+
textField.text = "Hello world"
111+
textField.becomeFirstResponder()
112+
113+
let container = ContainerView(control: textField)
114+
container.bounds.size = .init(width: 120, height: 44)
115+
116+
// This is testing flaky behavior, so run the test multiple times to ensure it's consistent.
117+
for _ in 0..<10 {
118+
SnapshotVerifyAccessibility(container)
119+
}
120+
121+
// Ensure the tint color is restored.
122+
XCTAssertEqual(textField.tintColor, .red)
123+
}
124+
104125
}
105126

106127
// MARK: -

Sources/AccessibilitySnapshot/Core/Swift/Classes/UIView+ImageRendering.swift

+26
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,22 @@ extension UIView {
4848
) throws -> UIImage {
4949
let renderer = UIGraphicsImageRenderer(bounds: bounds)
5050

51+
// Hide the cursor of text inputs to prevent test flakes.
52+
var viewTintsToRestore: [UIView: UIColor] = [:]
53+
recursiveForEach(viewType: UITextField.self) { inputView in
54+
viewTintsToRestore[inputView] = inputView.tintColor
55+
inputView.tintColor = .clear
56+
}
57+
recursiveForEach(viewType: UITextView.self) { inputView in
58+
viewTintsToRestore[inputView] = inputView.tintColor
59+
inputView.tintColor = .clear
60+
}
61+
defer {
62+
viewTintsToRestore.forEach { inputView, tintColor in
63+
inputView.tintColor = tintColor
64+
}
65+
}
66+
5167
var error: Error?
5268

5369
let snapshot = renderer.image { context in
@@ -191,4 +207,14 @@ extension UIView {
191207

192208
private static let tileSideLength: CGFloat = 2000
193209

210+
private func recursiveForEach<ViewType: UIView>(
211+
viewType: ViewType.Type,
212+
_ block: (ViewType) -> Void
213+
) {
214+
if let view = self as? ViewType {
215+
block(view)
216+
}
217+
subviews.forEach { $0.recursiveForEach(viewType: viewType, block) }
218+
}
219+
194220
}

0 commit comments

Comments
 (0)