在UIBarButtonItem上添加UISegmentedControl

在导航栏中加上分段控件是很常用的做法,效果如下:

复制代码
UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(80.0f, 8.0f, 300.0f, 30.0f) ]; 
    [segmentedControl insertSegmentWithTitle:@"最新上架" atIndex:0 animated:YES]; 
    [segmentedControl insertSegmentWithTitle:@"热销商品" atIndex:1 animated:YES];
    [segmentedControl insertSegmentWithTitle:@"促销商品" atIndex:2 animated:YES];
//[segmentedControl insertSegmentWithImage:[UIImageimageNamed:@"style12"] atIndex:0animated:YES];
    
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    //segmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
    segmentedControl.momentary = YES; 
    segmentedControl.multipleTouchEnabled=NO; 
    //segmentedControl.userInteractionEnabled=YES;
    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; 
    //segmentedControl.tintColor=[UIColor clearColor];
    
    UIBarButtonItem *homeBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    self.navigationItem.rightBarButtonItem = homeBarItem;
复制代码

对应的方法:

复制代码
-(void)segmentAction:(UISegmentedControl *)Segment{
    NSInteger index = Segment.selectedSegmentIndex;

    if (index == 0) {
    //最新上架
       NewestGoods *newestGoods = [[NewestGoods alloc] initWithNibName:@"NewestGoods" bundle:nil];
        newestGoods.navigationItem.title = @"最新上架";
       [self.navigationController pushViewController:newestGoods animated:YES];
    }else if (index == 1) {
    //热销商品 
        HotItems *hotItems = [[HotItems alloc] initWithNibName:@"HotItems" bundle:nil];
        hotItems.navigationItem.title = @"热销商品";
        [self.navigationController pushViewController:hotItems animated:YES];
    }else {
    //促销商品
        PromotionsGoods *promotionsGoods = [[PromotionsGoods alloc] initWithNibName:@"PromotionsGoods" bundle:nil];
        promotionsGoods.navigationItem.title = @"促销商品";
        [self.navigationController pushViewController:promotionsGoods animated:YES];
    }


}
复制代码


你可能感兴趣的:(action)