In Swift 5, What do I use as Notification.Name to get “resize” notifications?
NotificationCenter.default.addObserver(self, selector: #selector(self.resize(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
@objc func resize(notification: Notification) {
print ("resize");
}
I tried the aboe code, hoping to get some notifications. I get nothing.
Ronald Cordes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Hi,
I would recommend using GeometryReader
, if you build your Views declarative in SwiftUI
.
You can then use a State variable (@State
) and an .onChange
View Modifier to monitor changes in the Window Size.
Here is a example, in this example I use the maxWidh and maxHeight of the visible View
and set a GeometryReader
as Background
, with .onChange
we update the @State
Variable but we also can run other functions after after a change, (maybe debounced with Combine / Task …).
import SwiftUI
struct ContentView: View {
@State private var windowSize: CGSize = .zero
var body: some View {
VStack {
Text("Window: (Int(windowSize.width))x(Int(windowSize.height))")
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(GeometryReader { geometry in
Color.clear
.onAppear {
windowSize = geometry.size
}
.onChange(of: geometry.size) {
windowSize = geometry.size
}
})
}
}
More to GeometryReader
you can also find on Apples Documentation:
Geometry Reader (Apple Documentation)