(Swift)
import UIKit class ViewController: UIViewController { var segmentedControl:UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let segments = [ "iPhone", "iPad", "iPod", "iMac"] segmentedControl = UISegmentedControl(items: segments) segmentedControl.center = view.center segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: .ValueChanged) self.view.addSubview(segmentedControl) } func segmentedControlValueChanged(sender: UISegmentedControl){ let selectedSegmentIndex = sender.selectedSegmentIndex let selectedSegmentText = sender.titleForSegmentAtIndex(selectedSegmentIndex) println("Segment \(selectedSegmentIndex) with text" + " of \(selectedSegmentText) is selected") } }
(Objective-C)
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UISegmentedControl *mySegmentedControl; @end @implementation ViewController ... - (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]; [self.mySegmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; } - (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); } }
(Swift)
let segments = NSArray(objects: "Red", UIImage(named: "blueDot")!, "Green", "Yellow") segmentedControl = UISegmentedControl(items: segments)
(Objective-C)
NSArray *segments = @[ @"iPhone", [UIImage imageNamed:@"iPad"], @"iPod", @"iMac", ]; self.mySegmentedControl = [[UISegmentedControl alloc] initWithItems:segments]; CGRect segmentedFrame = self.mySegmentedControl.frame; segmentedFrame.size.height = 128.0f; segmentedFrame.size.width = 300.0f; self.mySegmentedControl.frame = segmentedFrame; self.mySegmentedControl.center = self.view.center; [self.view addSubview:self.mySegmentedControl];
时间: 2024-10-09 20:02:23