Custom UISegmentedControl(自定义 UISegmentedControl)
问题描述
如何制作自定义 UISegmentedControl
?
我有 2 张图片,其中 1 张应在段处于活动状态时显示,而另一张应在段处于非活动状态时显示.我可以覆盖样式或其他东西,所以我有一个 UISegmentedControl
与我自己的图像作为活动/非活动背景?
I have 2 images, 1 that should be displayed when the segment is active and the other if the segment is inactive. Can i override the style or something so i have a UISegmentedControl
with my own images as active/inactive background?
推荐答案
除了on"和off"位置有两种不同的状态之外,我还必须添加这个额外的代码:
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];
}
因为这得到了一些宣传,所以更简洁的解决方案是使用 [UIImage new] 而不是创建透明图像,例如:
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];
这篇关于自定义 UISegmentedControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!