iphone - 自定义 UISegmentedControl

标签 iphone objective-c cocoa-touch uikit uisegmentedcontrol

如何制作自定义 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/

相关文章:

ios - 如何以编程方式计算 UIImagePickerController 工具栏的高度?

ios - IBOutlet 不来

iphone - 将新的屏幕截图上传到 iTunes Connect

iphone - 如何在 UIWebView 中禁用复制和粘贴

iphone - 在不重复使用标识符的情况下使用多个自定义单元格

objective-c - 有没有办法只允许 UIViewControllers 遵守协议(protocol)?

iphone - 以编程方式访问应用标识符前缀

iphone - CLLocationManager 没有获取城市名称

ios - 如何在导航 Controller 中同时进行模式转换和弹出到根?

objective-c - 如何在下载后而不是在重新加载单元格后立即显示表格 View 图像