标签:
(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];
iOS开发技巧 - 使用UISegmentedControl来对信息进行分组
标签:
原文地址:http://www.cnblogs.com/davidgu/p/5773854.html