Created
October 23, 2023 19:20
-
-
Save ryanlintott/d694a905120b78a477991e75eb32ca42 to your computer and use it in GitHub Desktop.
SwiftUI Grid by default does not have a way to add accessibility labels to an entire row. This is an example workaround to provide that feature. It also provides a background view for each row but the colours can be set to Color.clear if you only want the accessibility label.
This file contains 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
// | |
// GridAccessibilityTest.swift | |
// FrameUpExample | |
// | |
// Created by Ryan Lintott on 2023-10-22. | |
// | |
import FrameUp | |
import SwiftUI | |
@available(iOS 17, tvOS 17, *) | |
struct GridAccessibilityTest: View { | |
@State private var rowHeights: [Int: CGFloat] = [:] | |
var body: some View { | |
ScrollView { | |
Grid(alignment: .leading) { | |
GridRow { | |
Text("Hello") | |
.accessibilityHidden(true) | |
.background(alignment: .leading) { | |
Color.blue | |
.containerRelativeFrame(.horizontal) | |
.frame(height: rowHeights[1]) | |
.accessibilityLabel("Hello World World") | |
} | |
Text("World World") | |
.accessibilityHidden(true) | |
} | |
.onSizeChange { size in | |
rowHeights[1] = max(size.height, rowHeights[1] ?? 0) | |
} | |
GridRow { | |
Text("Hello Hello") | |
.background(alignment: .leading) { | |
Color.red | |
.containerRelativeFrame(.horizontal) | |
.frame(height: rowHeights[2]) | |
.accessibilityLabel("Hello Hello World") | |
} | |
Text("World") | |
} | |
.accessibilityHidden(true) | |
.onSizeChange { size in | |
rowHeights[2] = max(size.height, rowHeights[2] ?? 0) | |
} | |
} | |
} | |
.scrollBounceBehavior(.basedOnSize, axes: .vertical) | |
.fixedSize(horizontal: false, vertical: true) | |
} | |
} | |
#Preview { | |
Group { | |
if #available(iOS 17, tvOS 17, *) { | |
GridAccessibilityTest() | |
.environment(\.dynamicTypeSize, .accessibility5) | |
} else { | |
// Fallback on earlier versions | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
onSizeChange is a modifier included in FrameUp. Preference keys can be used as an alternative.