segmented contro

[objc]  view plain copy 在CODE上查看代码片
  1. - (void)initSegmentedControl  
  2. {  
  3.     NSArray *segmentedData = [[NSArray alloc]initWithObjects:@"apple",@"orange",@"banana",nil];  
  4.     UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedData];  
  5.     segmentedControl.frame = CGRectMake(10.020.0,300.030.0);  
  6.     /* 
  7.      这个是设置按下按钮时的颜色 
  8.      */  
  9.     segmentedControl.tintColor = [UIColor colorWithRed:49.0 / 256.0 green:148.0 / 256.0 blue:208.0 / 256.0 alpha:1];  
  10.     segmentedControl.selectedSegmentIndex = 0;//默认选中的按钮索引  
  11.   
  12.   
  13.     /* 
  14.      下面的代码实同正常状态和按下状态的属性控制,比如字体的大小和颜色等 
  15.      */  
  16.     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12],NSFontAttributeName,[UIColor redColor], NSForegroundColorAttributeName, nil nil];  
  17.   
  18.   
  19.     [segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];  
  20.       
  21.       
  22.     NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];  
  23.       
  24.     [segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateHighlighted];  
  25.       
  26.     //设置分段控件点击相应事件  
  27.     [segmentedControl addTarget:self action:@selector(doSomethingInSegment:)forControlEvents:UIControlEventValueChanged];  
  28.       
  29.     [self.view addSubview:segmentedControl];  
  30. }  

 

每个功能注释都有清晰的描述,有一点要特别说明一下:

在ios7以前,segmentedcontrol有一个segmentedControlStyle 属性,通常都要设置,比如像下面这样:

[objc]  view plain copy 在CODE上查看代码片
  1. /* 
  2.      typedef enum { 
  3.      UISegmentedControlStylePlain, 
  4.      UISegmentedControlStyleBordered, 
  5.      UISegmentedControlStyleBar, 
  6.      UISegmentedControlStyleBezeled, 
  7.      } UISegmentedControlStyle; 
  8.  
  9.  */  
  10. segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;  


但是这个在ios7之后,出于扁平化风格的考虑,这些style都不在有效了

 

我们再写一个按钮的事件响应函数,设置不同的背景图片,如下:

[objc]  view plain copy 在CODE上查看代码片
  1. -(void)doSomethingInSegment:(UISegmentedControl *)Seg  
  2. {  
  3.       
  4.     NSInteger Index = Seg.selectedSegmentIndex;  
  5.       
  6.     switch (Index)  
  7.     {  
  8.         case 0:  
  9.             self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:kSrcName(@"bg_apple_small.png")]];  
  10.             break;  
  11.         case 1:  
  12.             self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:kSrcName(@"bg_orange_small.png")]];  
  13.             break;  
  14.         case 2:  
  15.             self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:kSrcName(@"bg_banana_small.png")]];  
  16.             break;  
  17.         default:  
  18.             break;  
  19.     }  
  20. }

你可能感兴趣的:(segmented contro)