SwiftUI - stack multiple method calls in parent view - swift

I am kind of a SwiftUI newbe but my question is essentially this:
I have a view that looks like this:
struct myView: View {
var label = Text("label")
var subLabel = Text("sublabel")
var body: some View {
VStack {
label
subLabel
}
}
public func primaryColor(color: Color) -> some View {
var view = self
view.label = view.label.foregroundColor(color)
return view.id(UUID())
}
public func secondaryColor(color: Color) -> some View {
var view = self
view.subLabel = view.subLabel.foregroundColor(color)
return view.id(UUID())
}
}
And here is my problem:
In my parent view, I would like to call myView as follows
struct parentView: View {
var body: some View {
myView()
.primaryColor(color: .red)
.secondaryColor(color: .blue)
}
}
Using only one of these modifiers works fine but stacking them won't work (since they return some View ?).
I don't think that I can use standard modifiers since I have to access myView variables, which (I think) wouldn't be possible by using a ViewModifier.
Is there any way to achieve my goal or am I going on the wrong direction ?

Here is a solution for you - remove .id (it is really not needed, result will be a copy anyway):
struct myView: View {
var label = Text("label")
var subLabel = Text("sublabel")
var body: some View {
VStack {
label
subLabel
}
}
public func primaryColor(color: Color) -> Self {
var view = self
view.label = view.label.foregroundColor(color)
return view
}
public func secondaryColor(color: Color) -> Self {
var view = self
view.subLabel = view.subLabel.foregroundColor(color)
return view
}
}
and no changes in parent view
Demo prepared with Xcode 13 / iOS 15

I'd suggest a refactor where primaryColor and secondaryColor can be passed as optional parameters to your MyView (in Swift, it is common practice to capitalize type names):
struct MyView: View {
var primaryColor : Color = .primary
var secondaryColor : Color = .secondary
var body: some View {
VStack {
Text("label")
.foregroundColor(primaryColor)
Text("sublabel")
.foregroundColor(secondaryColor)
}
}
}
struct ParentView: View {
var body: some View {
MyView(primaryColor: .red, secondaryColor: .blue)
}
}
This way, the code is much shorter and more simple, and follows the general form/practices of SwiftUI.
You could also use Environment keys/values to pass the properties down, but this takes more code (shown here for just the primary color, but you could expand it to secondary as well):
private struct PrimaryColorKey: EnvironmentKey {
static let defaultValue: Color = .primary
}
extension EnvironmentValues {
var primaryColor: Color {
get { self[PrimaryColorKey.self] }
set { self[PrimaryColorKey.self] = newValue }
}
}
extension View {
func primaryColor(_ primary: Color) -> some View {
environment(\.primaryColor, primary)
}
}
struct MyView: View {
#Environment(\.primaryColor) var primaryColor : Color
var body: some View {
VStack {
Text("label")
.foregroundColor(primaryColor)
}
}
}
struct ParentView: View {
var body: some View {
MyView()
.primaryColor(.red)
}
}

Related

SwiftUI polymorphic behaviour not working for View

protocol BackgroundContent: View{
}
struct BlueDivider: BackgroundContent {
var body: some View {
Divider()
.frame(minHeight: 1)
.background(.blue)
}
}
struct RedDivider: BackgroundContent {
var body: some View {
Divider()
.frame(minHeight: 1)
.background(.red)
}
}
var p: BackgroundContent = BlueDivider()
// Use of protocol 'BackgroundContent' as a type must be written 'any BackgroundContent'
p = RedDivider()
This always ask me to use
var p: any BackgroundContent = BlueDivider()
Is there any way to use generic type which accept any kind view?
Actually, I want to use view as a state like #State private var bgView: BackgroundContent = BlueDivider() which i want to change at runtime like bgView = RedDivider()
I have made my custome view to place some other view at runtime by using this state.
For your specific problem you can do something like this here:
struct SwiftUIView: View {
#State var isRed = false
var body: some View {
Devider()
.frame(height: 1)
.background(isRed ? Color.red : Color.blue)
}
}
It is complicated but i have found a solution of this problem. First thing i have done with ObservableObject. Here is my example.
protocol BaseBackgroundContent {
var color: Color { get set }
}
class BlueContent: BaseBackgroundContent {
var color: Color = .blue
}
class RedContent: BaseBackgroundContent {
var color: Color = .red
}
And i created a custom view for Divider in this case.
struct CustomDivider: View {
var backgroundContent: any BaseBackgroundContent
var body: some View {
Divider()
.background(backgroundContent.color)
}
}
And now i used a viewModel which can be observable, and the protocol has to be Published.
class ExampleViewModel: ObservableObject {
#Published var backgroundContent: any BaseBackgroundContent = RedContent()
func change() {
backgroundContent = BlueContent()
}
}
Final step is the view. This is a exampleView. If you click the button you will see the BlueContent which was RedContent
struct Example: View {
#ObservedObject var viewModel = ExampleViewModel()
init() {
}
var body: some View {
VStack {
Text("Test")
CustomDivider(backgroundContent: viewModel.backgroundContent)
Button("Change") {
viewModel.change()
}
}
}
}

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()
}
}
}
}

Is it possible to override a view modifier from a custom view?

Is it possible to override your own default modifier on a custom View? If not, is there any fancy way to adjust this without using an init?
Example
struct MainView: View {
var body: some View {
CustomView()
.font(.custom(weight: .medium, fontSize: 28)) // I want the custom view to change its' "sub"-font and use this modifier instead of using .footnote font.
}
}
struct CustomView: View {
var body: some View {
VStack {
Divider()
Text("Random")
.font(.footnote)
}
}
}
One solution is just to add an Font property in the CustomView init and use it inside the viewModifier like below. But would be gladly to know if it's possible to change it from its' parent viewModifier! I might just end up with using the solution below if it's not possible.
struct CustomView: View {
let customFont: Font = .callout
var body: some View {
VStack {
Divider()
Text("Random")
.font(customFont)
}
}
}
To make your MainView work we can use extension with custom implementation of font modifier, explicit for CustomView.
Here is a demo of approach (prepared & tested with Xcode 12.5 / iOS 14.5)
CustomView()
.font(.custom("Arial", size: 28, relativeTo: .caption))
struct CustomView: View {
private var customFont: Font = .footnote
var body: some View {
VStack {
Divider()
Text("Random")
.font(customFont)
}
}
}
extension CustomView {
func font(_ font: Font) -> some View {
var updatedView = self // make writable
updatedView.customFont = font // update in copy
return updatedView // return updated with external font
}
}
You can create one Appearance class and mention all the style property for your subview component and make an own function for all property inside the view.
Here is the demo code.
CustomViewAppearance
class CustomViewAppearance {
var customFont: Font = .footnote
var textColor: Color = .red
}
CustomView and property function.
struct CustomView: View {
private var appearance = CustomViewAppearance()
var body: some View {
VStack {
Divider()
Text("Random")
.font(appearance.customFont)
.foregroundColor(appearance.textColor)
}
}
}
extension CustomView {
func font(_ font: Font) -> some View {
self.appearance.customFont = font
return self
}
func foregroundColor(_ color: Color) -> some View {
self.appearance.textColor = color
return self
}
}
--
You can also set direct Appearance.
extension CustomView {
func appearance(_ appearance: CustomViewAppearance) -> some View {
var selfView = self
selfView.appearance = appearance
return selfView
}
}
struct MainView: View {
var body: some View {
CustomView()
.appearance(customStyle())
}
func customStyle() -> CustomViewAppearance {
let appearance = CustomViewAppearance()
appearance.customFont = .largeTitle
appearance.textColor = .yellow
return appearance
}
}

How can I use function type?

I want to know if there is a way to use a function Type as var, for example in this code I am trying to send a function to get triggered in a Button tap Action. Is this kind of programming even possible in Swift?
The down code is not working and It is for SwiftUI, but the question is applicable to Swift as well.
struct ContentView: View {
#State var backgroundColor: Color = Color.white
func backgroundColorFunction() { backgroundColor = Color.red }
var body: some View {
ZStack {
backgroundColor.ignoresSafeArea()
CustomView(incomingFuction: backgroundColorFunction()) // :Here
}
}
}
struct CustomView: View {
var incomingFuction: ???funcType??? = ???funcType???()
var body: some View {
Button("update Background Color") {
incomingFuction()
}
}
}
Yes, it is possible, moreover it is widely used, especially in SwiftUI.
Here is your updated code:
struct FuncContentView: View {
#State var backgroundColor: Color = Color.white
func backgroundColorFunction() { backgroundColor = Color.red }
var body: some View {
ZStack {
backgroundColor.ignoresSafeArea()
CustomView(incomingFuction: backgroundColorFunction) // << here !!
}
}
}
struct CustomView: View {
var incomingFuction: () -> () // << here !!
var body: some View {
Button("update Background Color") {
incomingFuction()
}
}
}

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")}
}
}
}