HomeiOS Developmentios - Swift UI: onAppear will get known as after view rendered

ios – Swift UI: onAppear will get known as after view rendered


I’m comparatively new to Swift UI and I’m attempting to create a number of randomly positioned button on the display screen utilizing a random quantity generator and an array to retailer these random quantity with a purpose to be sure that I do not render two button on the identical place. The issue I’m going through is that whereas I get the random quantity’s displayed, I’m unable to replace the array in time for the perform to verify if the quantity has already been chosen.

That is my present answer

ButtonView:

struct ButtonView: View {
    func handleButton() {
        //DO SOMETHING  
    }
    
    var physique: some View {
        let randX = Int(getRandomX(maxScreenWidth: 350))
        Button(motion: handleBubbleButtonClick) {
            Textual content("Bubble (randX)")
        }.onAppear {
            print("ADDING : (randX)")
            CommonAppParameters.shared.plottedXPoints.append(randX)
        }
    }
    
}

Widespread

class CommonAppParameters {
    static let shared = CommonAppParameters()
        var plottedXPoints: [Int] = []
        var plottedYPoints: [Int] = []
    }
    
    func getRandomX(maxScreenWidth: Int) -> CGFloat {
        let maxWidth = maxScreenWidth
        let plottedXPoints = CommonAppParameters.shared.plottedXPoints
    
        guard maxWidth > 0 else {
            return CGFloat(0)
        }
        
        let highestPoint = maxWidth/2 - 20;
        let lowestPoint = -maxWidth/2 + 20;
        
        let randomNumber: Int = Int.random(in: lowestPoint...highestPoint);
        
        for level in plottedXPoints {
            let vary = point-20...level+20
            if (vary ~= randomNumber) {
                return getRandomX(maxScreenWidth: maxWidth)
            }
        }
        
        //If I attempt including it right here, for some motive the appliance crashes, I'd respect it if somebody may clarify why?    
        //CommonAppParameters.shared.plottedXPoints.append(randomNumber)
        return CGFloat(randomNumber)
    }
}

MainView

struct MainView: View {
    var physique: View {
        VStack {
            ForEach((1...10), id: .self) { one thing in 
                ButtonView()    
        }
    }
}

Expectation

I needed the plottedXPoints array to fill because the button’s have been rendered, however what is going on is that the buttons get rendered with totally different random X factors and the array get full of totally different ones.

Utility UI

Console UI

These each ought to comprise the identical numbers for this to work correctly. Any assist can be appreciated.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments