如何制作自定义 UISegmentedControl
?
我有 2 张图片,其中 1 张应在段处于事件状态时显示,而另一张应在段处于非事件状态时显示。我可以覆盖样式或其他东西,所以我有一个 UISegmentedControl
与我自己的图像作为事件/非事件背景?
最佳答案
除了“开”和“关”位置有两种不同的状态外,我还必须添加这个额外的代码:
- (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] 而不是创建透明图像,例如:
[self.segControl setDividerImage:[UIImage new] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.segControl setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
关于iphone - 自定义 UISegmentedControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1281601/