Learn the iOS switch button UISwitch control

  • 2020-06-23 02:02:44
  • OfStack

This article examples for you to share iOS switch button UISwitch control specific code, for your reference, specific content is as follows

In ViewController h inside


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

 // define 1 A switch control 
 // Effects can make state changes 
 // open , Close: The two states can be switched 
 // all UIKit The controls in the framework library have been removed UI At the beginning 
 // Apple's official controls are defined in UIKit In the framework of library 
 UISwitch * _mySwitch;

}

@property(retain,nonatomic) UISwitch * mySwitch;


@end

In ViewController m inside


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize mySwitch=_mySwitch;

- (void)viewDidLoad {
 [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.

 // create 1 Ten switch objects 
 // Inheritance in UIView the 
 _mySwitch = [[UISwitch alloc]init];

 // Apple's official control location Settings 
 // location X,Y Can be changed ( 100 . 100 ) 
 // The width and height values cannot be changed (80,40) It won't work. It won't work. The default. 
 _mySwitch.frame=CGRectMake(100, 200, 180, 40);

 // On/off state setting properties 
 //YES: open 
 //NO: The closed position 
 _mySwitch.on=YES;

 // You can also use set function 
 //[_mySwitch setOn:YES];

 // Set switching state 
 //p1: state 
 //p2: Whether to turn on animation 
 //[_mySwitch setOn:YES animated:YES];

 [self.view addSubview:_mySwitch];

 // Sets the style color for the enabled state 
 [_mySwitch setOnTintColor:[UIColor orangeColor]];

 // Set the style color of the switch circle button 
 [_mySwitch setThumbTintColor:[UIColor blueColor]];

 // Set the overall style color , The white of the button is the background color of the entire parent layout 
 [_mySwitch setTintColor:[UIColor greenColor]];

 // Adds an event function to the switch control 
 //p1: Function implementation object 
 //p2: The function object 
 //p3: The event type at the time of the event response UIControlEventValueChanged Triggers the function when the state changes 
 [_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];


}

// Parameter passed into the switch object itself 
- (void) swChange:(UISwitch*) sw{

 if(sw.on==YES){
  NSLog(@" Switch on ");
 }else{
  NSLog(@" Switch off ");
 }
}

- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

@end

Related articles: