IOS 7 Study - UISegmentedControl

本文介绍如何在iOS应用中使用UISegmentedControl创建简洁易懂的用户界面,包括声明控制、创建控件、添加事件监听及处理段选变化的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值