iOS基础 -- UISegmentControl

/**
     *  UISegmentContorl
     */
    
    NSArray *items = [[NSArray alloc] initWithObjects:@"iPhone",@"iPad",@"iPod",@"iMac", nil];
    self.mySegmentControl = [[UISegmentedControl alloc] initWithItems:items];
    
    //NSArray *segments = @[@"iPhone",[UIImage imageNamed:@"ipad.png"],@"iPod",@"iMac"];
    //self.mySegmentControl = [[UISegmentedControl alloc] initWithItems:segments];
    //CGRect segmentFrame = self.mySegmentControl.frame;
    //segmentFrame.size.width = 300.0f;
    //segmentFrame.size.height = 128.0f;
    //self.mySegmentControl.frame = segmentFrame;
    
    self.mySegmentControl.center = self.view.center;
    [self.mySegmentControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
    //self.mySegmentControl.momentary = YES;//won't remain the state
    [self.view addSubview:self.mySegmentControl];

以上是添加UISegmentControl到当前view。target方法如下:

-(void) segmentChanged:(UISegmentedControl *)paramSender
{
    if([paramSender isEqual:self.mySegmentControl]){
        NSUInteger segmentIndex = [paramSender selectedSegmentIndex];
        NSString *segmentTitle = [paramSender titleForSegmentAtIndex:segmentIndex];
        NSLog(@"segment at %ld is %@",(long)segmentIndex,segmentTitle);
    }
}

上面的属性设置部分,值得注意的时momentary属性,这个属性表达为在是否只有在操作时,才短暂保留当前的选中的状态,默认状态是NO。

此外UISegmentControl中,各分段也可以是图文混合的方式。当然元素仅限NSString和UIImage两种形式。官方声明如下:

- (id)initWithItems:(NSArray *)items; // items can be NSStrings or UIImages. control is automatically sized to fit content
默认是自适应高宽,当然也可以如上例所示自己通过修改frame去修改。

在iOS7中,官方已经弃用了UISegmentControl的segmentedControlStyle属性。

你可能感兴趣的:(iOS)