Skip to content

Commit

Permalink
Fixed modifier for device orientation.
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanvorobei committed Sep 10, 2023
1 parent 87f135f commit e98b133
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions Sources/SwiftUIExtension/Extensions/ViewExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,11 @@ extension View {
self.onReceive(NotificationCenter.default.publisher(for: name), perform: action)
}

public func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
self.modifier(DeviceRotationViewModifier(action: action))
}

public func containerBackgroundForWidget<Background>(background: @escaping () -> Background) -> some View where Background: View {
public func containerBackgroundForWidget<Background>(@ViewBuilder background: @escaping () -> Background) -> some View where Background: View {
modifier(ContainerBackgroundForWidgetModifier(background: background))
}
}

struct DeviceRotationViewModifier: ViewModifier {

let action: (UIDeviceOrientation) -> Void

func body(content: Content) -> some View {
content
.onAppear()
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
action(UIDevice.current.orientation)
}
}
}

struct ContainerBackgroundForWidgetModifier<Background>: ViewModifier where Background: View {

let background: () -> Background
Expand All @@ -47,3 +30,27 @@ struct ContainerBackgroundForWidgetModifier<Background>: ViewModifier where Back
}
}
}

// MARK: - Only iOS

#if os(iOS)
extension View {

public func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
self.modifier(DeviceRotationViewModifier(action: action))
}
}

struct DeviceRotationViewModifier: ViewModifier {

let action: (UIDeviceOrientation) -> Void

func body(content: Content) -> some View {
content
.onAppear()
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
action(UIDevice.current.orientation)
}
}
}
#endif

0 comments on commit e98b133

Please sign in to comment.