Move Button to front programmatically

Discussion in 'iOS Programming' started by nickculbertson, Jan 24, 2011.

  1. macrumors regular

    nickculbertson

    Joined:
    Nov 19, 2010
    Location:
    Nashville, TN
    #1
    Hello,
    I have a number of UIButtons moving in an animation where they overlap. Is there a way to programmatically move one button in front of another when passing a given coordinate?

    Code:
    - (IBAction) onTimer1 {
    	button1.center = CGPointMake(button1.center.x+pos1.x,button1.center.y+pos1.y);
    	
    	if (button1.center.x > 270|| button1.center.x+pos1.y < 55) 
    		pos1.x = -pos1.x;
    	if (button1.center.y > 400|| button1.center.y+pos1.y < 292.5) 
    		pos1.y = -pos1.y;
    	if (button1.center.y > 395)
    		button1.transform = CGAffineTransformMakeScale(1, 1);
    //Here is where I want to move to front.
    	if (button1.center.y < 394)
    		button1.transform = CGAffineTransformMakeScale(.5, .5); //...
    //Here is where I want to move to back.
    }
    	
    Thanks,
    Nick
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    The only way I can think of doing it would be to alter the zPosition property of the buttons layer to position it above the other buttons.
     
  3. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    Well, there's the possibility of UIView's bringSubviewToFront:
     
  4. thread starter macrumors regular

    nickculbertson

    Joined:
    Nov 19, 2010
    Location:
    Nashville, TN
    #4
    Thank you, Sir. That seemed to do the trick.

    Code:
    - (IBAction) onTimer1 {
    	button1.center = CGPointMake(button1.center.x+pos1.x,button1.center.y+pos1.y);
    	
    	if (button1.center.x > 270|| button1.center.x+pos1.y < 55) 
    		pos1.x = -pos1.x;
    	if (button1.center.y > 400|| button1.center.y+pos1.y < 292.5) 
    		pos1.y = -pos1.y;
    	if (button1.center.y > 395){
    		button1.transform = CGAffineTransformMakeScale(1, 1);
    button1.layer.zPosition=5.0f;
    }
    	if (button1.center.y < 394){
    		button1.transform = CGAffineTransformMakeScale(.5, .5); //...
    button1.layer.zPosition=-5.0f;
    }
    }
    
    Nick
     
  5. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    I suspect that does the same thing in one handy call so is probably a better option, yes :)
     
  6. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    Yeah, I wasn't sure if the OP was wanting to move the view to the very front or just higher up in the z-index, so that's why I said "possibly". :)
     

Share This Page