Home > other >  SceneKit: How to arrange buttons in ascending order using for in loop?
SceneKit: How to arrange buttons in ascending order using for in loop?

Time:11-26

The task is to add 10 buttons (0...9) with labels using for in loop. I created buttons based on class ButtonPrototype. I assigned label to each button via counter inside for in loop.

It works, but there is incorrect labels order:

enter image description here

I need another order:

enter image description here

How can I implement correct order?

Code:

func createButtons() {
    
    for y in 0...1 {
        
        for x in 0...4 {
            
            counterForLoop  = 1
            
            self.button = ButtonPrototype(pos: .init(  CGFloat(x)/7, CGFloat(y)/7, 0 ), imageName: "\(counterForLoop)")
            
            parentNode.addChildNode(button)
            
            parentNode.position = SCNVector3(x: 100,
                                             y: 100,
                                             z: 100)
        }
    }
}

CodePudding user response:

You have at least two problems with your code. Your smallest button label is in the lower left and you want it to be in the lower right, and your labels go 0-9, and you want them to go from 1 to 10 (but display 10 as “0”).

To reverse the x ordering, change X to 10-x in your creation of a position, and change your imageName to “((counterForLoop 1))”:

self.button = ButtonPrototype(
    pos: .init(  
        CGFloat(10-x)/7, 
        CGFloat(y)/7, 
        0), 
    imageName: "\((counterForLoop 1))")

By the way, you should add a SceneKit tag to your question. That seems more important than either the label tag or the loops tag.

CodePudding user response:

The following approach perfectly makes the trick:

for y in 0...1 {

    for x in 0...4 {

        let textNode = SCNNode()
        let ascendingOrder: String = "\(((x 1) (y*5)) % 10)"
        
        let geo = SCNText(string: ascendingOrder, extrusionDepth: 0.5)
        geo.flatness = 0.04
        geo.firstMaterial?.diffuse.contents = UIImage(named: ascendingOrder)
        textNode.geometry = geo

        textNode.position = SCNVector3(x*10, -y*10, 0)
        sceneView.scene?.rootNode.addChildNode(textNode)
        print(ascendingOrder)
    }
}

enter image description here

  • Related