Monday, 17 June 2013

How to create UISwitch programatically in cocos2d

UISwitch is mainly used for representing two states. Normal UISwitch has 2 states: ON and OFF respectively.




Creating UISwitch in your cocos2d application is very simple. The steps for creating an UISwitch is described below:
       
First create an UIView:

        UIView *profileView = [[UIView alloc] init];
        profileView.frame = CGRectMake(0, 50, 320, 395);
        profileView.backgroundColor = [UIColor clearColor];
        [[[CCDirector sharedDirector] openGLView] addSubview:profileView];
   
Then you can create the switch and add to the UIView:

        UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(130, 235, 0, 0)];
        [mySwitch addTarget:self action:@selector(changeSwitch:)
                               forControlEvents:UIControlEventValueChanged];
        [profileView addSubview:mySwitch];

When the state of the switch is changed, it will trigger the following function:       

        -(void)changeSwitch:(UISwitch *)mySwitch{
                   // By NSLog, you can get the current state of the switch
                   NSLog(@"%@", mySwitch.on ? @"On" : @"Off");
        }

No comments:

Post a Comment