Created
December 4, 2020 21:52
-
-
Save Rspoon3/d02ee7532f07238e5ad313e4b6553b74 to your computer and use it in GitHub Desktop.
Setting equal widths in swiftUI.
This file contains hidden or 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
| import SwiftUI | |
| struct ContentView: View { | |
| @State var width: CGFloat? = nil | |
| var body: some View { | |
| Form{ | |
| ForEach(0..<115){ i in | |
| Row(place: i, width: $width) | |
| } | |
| }.modifier(ColumnWidth(width:$width)) | |
| } | |
| } | |
| struct ContentView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| ContentView() | |
| } | |
| } | |
| struct Row: View{ | |
| let place: Int | |
| @Binding var width: CGFloat? | |
| func formatted()->String{ | |
| let value = NSNumber(value: place + 1) | |
| let formatter = NumberFormatter() | |
| formatter.numberStyle = .ordinal | |
| return formatter.string(from: value)! | |
| } | |
| var body: some View{ | |
| HStack{ | |
| Text(formatted()) | |
| .frame(width: width, alignment: .leading) | |
| .background(ColumnWidthEqualiserView()) | |
| Color.red | |
| .frame(width: 30, height: 30) | |
| .clipShape(Circle()) | |
| Text("Name") | |
| Spacer() | |
| Text("Details go here") | |
| .foregroundColor(.gray) | |
| } | |
| } | |
| } | |
| struct ColumnWidthPreference: Equatable { | |
| let width: CGFloat | |
| } | |
| struct ColumnWidthPreferenceKey: PreferenceKey { | |
| typealias Value = [ColumnWidthPreference] | |
| static var defaultValue: [ColumnWidthPreference] = [] | |
| static func reduce(value: inout [ColumnWidthPreference], nextValue: () -> [ColumnWidthPreference]) { | |
| value.append(contentsOf: nextValue()) | |
| } | |
| } | |
| struct ColumnWidthEqualiserView: View { | |
| var body: some View { | |
| GeometryReader { geometry in | |
| Rectangle() | |
| .fill(Color.clear) | |
| .preference( | |
| key: ColumnWidthPreferenceKey.self, | |
| value: [ColumnWidthPreference(width: geometry.frame(in: CoordinateSpace.global).width)] | |
| ) | |
| } | |
| } | |
| } | |
| struct ColumnWidth: ViewModifier { | |
| @Binding var width: CGFloat? | |
| func body(content: Content) -> some View { | |
| content | |
| .onPreferenceChange(ColumnWidthPreferenceKey.self) { preferences in | |
| for p in preferences { | |
| let oldWidth = self.width ?? CGFloat.zero | |
| if p.width > oldWidth { | |
| self.width = p.width | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment