Custom UISegmentedControl

后端 未结 10 2072
我寻月下人不归
我寻月下人不归 2020-12-04 10:23

How do I make a custom UISegmentedControl?

I have 2 images, 1 that should be displayed when the segment is active and the other if the segment is inacti

10条回答
  •  攒了一身酷
    2020-12-04 10:40

    I had to add this extra code, in addition to having 2 different states for the "on" and "off" positions:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        // Set set segControl background to transparent
        CGRect rect = CGRectMake(0, 0, 1, 1);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        CGContextFillRect(context, rect);
        UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        [self.segControl setBackgroundImage:transparentImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
        [self.segControl setDividerImage:transparentImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    }
    

    EDIT: Because this is getting some publicity, a cleaner solution is to use [UIImage new] instead of creating transparent images, as such:

     [self.segControl setDividerImage:[UIImage new] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
     [self.segControl setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    

提交回复
热议问题