Skip to content

Commit

Permalink
feat: add readSize view modifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
EnesKaraosman committed Apr 10, 2024
1 parent 31fceaa commit bf96c0d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,19 @@ Table of Contents

# Extensions

```swift
TextField("Input", text: $text, axis: .vertical)
.textFieldStyle(.roundedBorder)
.readSize {
print("size: \($0)")
}
```

### Keyboard related modifiers (iOS only)

```swift
AwesomeView()
.onKeyboardAppear { heigth in

}
.onKeyboardAppear { heigth in }
```

### Platform based modifiers
Expand Down
25 changes: 24 additions & 1 deletion Sources/SwiftUIEKtensions/Extensions/View+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,32 @@ public extension View {
return self
#endif
}


/// Read view's size and bind it to `size` property
func readSize(to size: Binding<CGSize>) -> some View {
readSize { size.wrappedValue = $0 }
}

/// Read view's size and take action on change
func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { proxy in
Color.clear
.preference(
key: SizePreferenceKey.self,
value: proxy.size
)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}

struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero

static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

public enum Platform {
case iOS
Expand Down

0 comments on commit bf96c0d

Please sign in to comment.