IOS 7 Study

You would like to present a few options to your users from which they can pick an
option, through a UI that is compact, simple, and easy to understand.

effect:

 1. declare control

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UISegmentedControl *mySegmentedControl;

@end

@implementation ViewController

 2. create the segmented control in the viewDidLoad method of your view controller

- (void)viewDidLoad {
  [super viewDidLoad];

  NSArray *segments = [[NSArray alloc] initWithObjects:
        @"iPhone",
        @"iPad",
        @"iPod",
        @"iMac", nil];

  self.mySegmentedControl = [[UISegmentedControl alloc]
                                            initWithItems:segments];
  self.mySegmentedControl.center = self.view.center;
  [self.view addSubview:self.mySegmentedControl];
}


3. use the addTarget:action:forControlEvents: method of the segmented control to

  recognize when the user selects a new option

   // add event listener
  [self.mySegmentedControl addTarget:self
      action:@selector(segmentChanged:)
      forControlEvents:UIControlEventValueChanged];

- (void)viewDidLoad {
  [super viewDidLoad];

  NSArray *segments = @[
    @"iPhone",
    @"iPad",
    @"iPod",
    @"iMac"
  ];
  
  self.mySegmentedControl = [[UISegmentedControl alloc]
                              initWithItems:segments];

  self.mySegmentedControl.center = self.view.center;

  [self.view addSubview:self.mySegmentedControl];

  [self.mySegmentedControl addTarget:self
         action:@selector(segmentChanged:)
         forControlEvents:UIControlEventValueChanged];
}

4. segment change event

- (void) segmentChanged:(UISegmentedControl *)paramSender {
  if ([paramSender isEqual:self.mySegmentedControl]) {
    NSInteger selectedSegmentIndex = [paramSender   selectedSegmentIndex];
NSString
*selectedSegmentText = [paramSender titleForSegmentAtIndex:selectedSegmentIndex]; NSLog(@"Segment %ld with %@ text is selected", (long)selectedSegmentIndex, selectedSegmentText); } }

result on console:

Segment 0 with iPhone text is selected
Segment 1 with iPad text is selected
Segment 2 with iPod text is selected
Segment 3 with iMac text is selected

If no item is selected, this method returns the value –1

 

原文地址:https://www.cnblogs.com/davidgu/p/3543411.html