Making a view type environment in SwiftUI - swift

I want make an environment that carry view and the view that is going be carried is the ContentView, I made the first codes but since it is view and generic I have issue with generic type for my environment.
Some of Xcode error are like this:
Generic parameter 'Content' could not be inferred
Reference to generic type 'ViewType' requires arguments in <...>
My goal is building the environment that can carry a view like ContentView.
import SwiftUI
#main
struct Adv_view_sendrApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.rootMirrorContent, ViewType(content: ContentView()))
}
}
}
struct ContentView: View {
#Environment(\.rootMirrorContent) var rootMirrorContent
var body: some View {
Color.yellow
.overlay(Text("Hello, world!"))
.overlay(rootMirrorContent.scaleEffect(0.25).border(Color.black), alignment: .bottomTrailing)
}
}
struct RootMirrorContentEnvironmentKey: EnvironmentKey { static let defaultValue: ViewType = ViewType(content: <#() -> _#>) }
extension EnvironmentValues {
var rootMirrorContent: ViewType {
get { return self[RootMirrorContentEnvironmentKey.self] }
set(newValue) { self[RootMirrorContentEnvironmentKey.self] = newValue }
}
}
struct ViewType<Content: View>: View {
let content: () -> Content
var body: some View {
return content()
}
}

Related

How I can help struct infer View type values in a closure that feeds the needed type in SwiftUI?

The code below works:
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: { view in CustomModifier(content: { view } )} )
}
}
struct CustomModifier<Content: View>: View {
let content: () -> Content
var body: some View {
content()
.foregroundColor(.red)
}
}
extension View {
func customViewModifier<ContentModifier: View>(modifier: (Self) -> ContentModifier) -> some View {
return modifier(self)
}
}
My goal is to be able the code below. Currently, Xcode does not help me to fix the error.
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: CustomModifier)
}
}
Is there a way around to make my goal possible?
here was my try to solve the issue:
extension View {
func customViewModifier2<ContentModifier: View>(modifier: (Self) -> ((Self) -> ContentModifier)) -> some View {
return modifier(self)
}
}
Error:
Type '(Self) -> ContentModifier' cannot conform to 'View'
The final real goal is not clear ('cause it is really better to use ViewModifier based approach), but if you want to use a type as argument it can be like the following
*compiled with Xcode 13.2 / iOS 15.2
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.customViewModifier(modifier: CustomModifier.self) // << type !!
}
}
extension View {
func customViewModifier(modifier: CustomModifier<Self>.Type) -> some View {
return modifier.init(content: { self })
}
}

if with ScrollTo in SwiftUI

Sorry for the newbie question, but I'm trying to implement a scrollview with a logical text based on a preference value relating to an .id passed to the view. The code is something like this, but I keep getting a Type () cannot conform to 'View' error:
ScrollViewReader {proxy in
ScrollView (.vertical) {
if (preferences.scrollPosition != 0) {
withAnimation {
proxy.scrollTo(preferences.scrollPosition)
}
}
Updating my post: I was incorrect with the ordering
I'm just trying to put together a more concrete example for reference, is this similar to what you want/have?
import SwiftUI
class Preferences: ObservableObject {
#Published var scrollPosition: UnitPoint = .center
}
struct TestView: View {
#StateObject var preferences = Preferences()
var body: some View {
ScrollViewReader {proxy in
ScrollView (.vertical) {
}
.onAppear(perform: {
if (preferences.scrollPosition != .zero) {
withAnimation {
proxy.scrollTo(preferences.scrollPosition)
}
}
})
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}

I'm trying to implement a view stack in swiftui and my #State objects are being reset for reasons that are unclear to me

I'm new to swiftui and doing an experiment with pushing and popping views with a stack. When I pop a view off the stack, the #State variable of the prior view has been reset and I don't understand why.
This demo code was tested on macos.
import SwiftUI
typealias Push = (AnyView) -> ()
typealias Pop = () -> ()
struct PushKey: EnvironmentKey {
static let defaultValue: Push = { _ in }
}
struct PopKey: EnvironmentKey {
static let defaultValue: Pop = {() in }
}
extension EnvironmentValues {
var push: Push {
get { self[PushKey.self] }
set { self[PushKey.self] = newValue }
}
var pop: Pop {
get { self[PopKey.self] }
set { self[PopKey.self] = newValue }
}
}
struct ContentView: View {
#State private var stack: [AnyView]
var body: some View {
currentView()
.environment(\.push, push)
.environment(\.pop, pop)
.frame(width: 600.0, height: 400.0)
}
public init() {
_stack = State(initialValue: [AnyView(AAA())])
}
private func currentView() -> AnyView {
if stack.count == 0 {
return AnyView(Text("stack empty"))
}
return stack.last!
}
public func push(_ content: AnyView) {
stack.append(content)
}
public func pop() {
stack.removeLast()
}
}
struct AAA : View {
#State private var data = "default text"
#Environment(\.push) var push
var body: some View {
VStack {
TextEditor(text: $data)
Button("Push") {
self.push(AnyView(BBB()))
}
}
}
}
struct BBB : View {
#Environment(\.pop) var pop
var body: some View {
VStack {
Button("Pop") {
self.pop()
}
}
}
}
If I type some text into the editor then hit Push, then Pop out of that view, I was expecting the text editor to maintain my changes but it reverts to the default text.
What am I missing?
Edit:
I guess this is really a question of how are NavigationView and NavigationLink implemented. This simple code does the what I'm trying to do:
import SwiftUI
struct MyView: View {
#State var text = "default text"
var body: some View {
VStack {
TextEditor(text: $text)
NavigationLink(destination: MyView()) {
Text("Push")
}
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
MyView()
}
}
}
run that on iOS so you get a nav stack. edit the text, then push. Edit again if you want, then go back and see state is retained.
My code is trying to do the same thing in principle.
I'll share this attempt maybe it will help you create your version of this.
This all started with an attempt to create something like NavigationView and NavigationLink but being able to back track to a random View in the stack
I have a protocol where an object returns a View. Usually it is an enum. The view() references a View with a switch that provides the correct child View. The ContentView/MainView works almost like a storyboard and just presents whatever is designated in the current or path variables.
//To make the View options generic
protocol ViewOptionsProtocol: Equatable {
associatedtype V = View
#ViewBuilder func view() -> V
}
This is the basic navigation router that keep track of the main view and the NavigationLink/path. Which looks similar to what you want to do.
//A generic Navigation Router
class ViewNavigationRouter<T: ViewOptionsProtocol>: ObservableObject{
//MARK: Variables
var home: T
//Keep track of your current screen
#Published private (set) var current: T
//Keep track of the path
#Published private (set) var path: [T] = []
//MARK: init
init(home: T, current: T){
self.home = home
self.current = current
}
//MARK: Functions
//Control how you get to the screen
///Navigates to the nextScreen adding to the path/cookie crumb
func push(nextScreen: T){
//This is a basic setup just going forward
path.append(nextScreen)
}
///Goes back one step in the path/cookie crumb
func pop(){
//Use the stored path to go back
_ = path.popLast()
}
///clears the path/cookie crumb and goes to the home screen
func goHome(){
path.removeAll()
current = home
}
///Clears the path/cookie crumb array
///sets the current View to the desired screen
func show(nextScreen: T){
goHome()
current = nextScreen
}
///Searches in the path/cookie crumb for the desired View in the latest position
///Removes the later Views
///sets the nextScreen
func dismissTo(nextScreen: T){
while !path.isEmpty && path.last != nextScreen{
pop()
}
if path.isEmpty{
show(nextScreen: nextScreen)
}
}
}
It isn't an #Environment but it can easily be an #EnvrionmentObject and all the views have to be in the enum so the views are not completely unknown but it is the only way I have been able to circumvent AnyView and keep views in an #ViewBuilder.
I use something like this as the main portion in the main view body
router.path.last?.view() ?? router.current.view()
Here is a simple implementation of your sample
import SwiftUI
class MyViewModel: ViewNavigationRouter<MyViewModel.ViewOptions> {
//In some view router concepts the data that is /preserved/shared among the views is preserved in the router itself.
#Published var preservedData: String = "preserved"
init(){
super.init(home: .aaa ,current: .aaa)
}
enum ViewOptions: String, ViewOptionsProtocol, CaseIterable{
case aaa
case bbb
#ViewBuilder func view() -> some View{
ViewOptionsView(option: self)
}
}
struct ViewOptionsView: View{
let option: ViewOptions
var body: some View{
switch option {
case .aaa:
AAA()
case .bbb:
BBB()
}
}
}
}
struct MyView: View {
#StateObject var router: MyViewModel = .init()
var body: some View {
NavigationView{
ScrollView {
router.path.last?.view() ?? router.current.view()
}
.toolbar(content: {
//Custom back button
ToolbarItem(placement: .navigationBarLeading, content: {
if !router.path.isEmpty {
Button(action: {
router.pop()
}, label: {
HStack(alignment: .center, spacing: 2, content: {
Image(systemName: "chevron.backward")
if router.path.count >= 2{
Text(router.path[router.path.count - 2].rawValue)
}else{
Text(router.current.rawValue)
}
})
})
}
})
})
.navigationTitle(router.path.last?.rawValue ?? router.current.rawValue)
}.environmentObject(router)
}
}
struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
}
}
struct AAA : View {
//This will reset because the view is cosmetic. the data needs to be preserved somehow via either persistence or in the router for sharing with other views.
#State private var data = "default text"
#EnvironmentObject var vm: MyViewModel
var body: some View {
VStack {
TextEditor(text: $data)
TextEditor(text: $vm.preservedData)
Button("Push") {
vm.push(nextScreen: .bbb)
}
}
}
}
struct BBB : View {
#EnvironmentObject var vm: MyViewModel
var body: some View {
VStack {
Button("Pop") {
vm.pop()
}
}
}
}

Passing data from extension in SwiftUI

I am building a complex interface in SwiftUI that I need to break into multiple extensions in order to be able to compile the code, but I can't figure out how to pass data between the extension and the body structure.
I made a simple code to explain it :
class Search: ObservableObject {
#Published var angle: Int = 10
}
struct ContentView: View {
#ObservedObject static var search = Search()
var body: some View {
VStack {
Text("\(ContentView.self.search.angle)")
aTest()
}
}
}
extension ContentView {
struct aTest: View {
var body: some View {
ZStack {
Button(action: { ContentView.search.angle = 11}) { Text("Button")}
}
}
}
}
When I press the button the text does not update, which is my issue. I really appreciate any help you can provide.
You can try the following:
struct ContentView: View {
#ObservedObject var search = Search()
var body: some View {
VStack {
Text("\(ContentView.self.search.angle)")
aTest // call as a computed property
}
}
}
extension ContentView {
var aTest: some View { // not a separate `struct` anymore
ZStack {
Button(action: { self.search.angle = 11 }) { Text("Button")}
}
}
}

Can I make a protocol that inherits from 'View' to display a specific 'View'?

I'm trying to make some SwiftUI-Views with similar properties. So I want to make a protocol for them and display an instance of this protocol.
protocol SpecialView: View { ... }
struct SpecialViewA : View, SpecialView {
...
var body: some View {
Text("Hello World!")
}
}
struct ContentView: View {
var currentlyDisplayedView: some SpecialView
var body: some View{
currentlyDisplayedView
}
}
//in preview:
ContentView(SpecialViewA())
I expect the ContentView to accept my SpecialViewA as a SpecialView. However, in the preview I get
"Cannot convert value of type 'SpecialViewA' to expected argument type 'some SpecialView'".
and when trying to display I get:
"[...] requires that 'some SpecialView' conform to 'View'"
What am I doing wrong? Is there an easier way?
You were close..., but this will compile:
protocol SpecialView: View {
}
struct SpecialViewA : View, SpecialView {
var body: some View {
Text("Hello World!")
}
}
struct ContentView<V>: View where V: SpecialView {
var currentlyDisplayedView: V
var body: some View{
currentlyDisplayedView
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(currentlyDisplayedView: SpecialViewA())
}
}
#endif