【问题标题】:Customize uiswitch image properly?正确自定义uiswitch图像?
【发布时间】:2013-05-03 00:47:58
【问题描述】:

我的 iOS 6 应用程序中有一个 UISwitch,它是自定义的开关图像。

self.testSwitch.onImage = [UIImage imageNamed:@"on"]; 
self.testSwitch.offImage = [UIImage imageNamed:@"off"];

我为此使用了 77 点宽和 22 点高的图像(视网膜中为 154x44),如文档中所述。但是我的图像不适合我的 uiswitch,看起来很丑,默认样式隐藏了我的,就像在附加的图像上一样。

我应该如何设置才能使其正常工作?

【问题讨论】:

标签: ios xcode customization uiswitch


【解决方案1】:

这里是code from my book。这并不完全是您想要做的,但它展示了这项技术并将帮助您入门!请注意,我使用的是 79 x 27(不确定您的号码是从哪里得到的):

UIGraphicsBeginImageContextWithOptions(CGSizeMake(79,27), NO, 0);
[[UIColor blackColor] setFill];
UIBezierPath* p = [UIBezierPath bezierPathWithRect:CGRectMake(0,0,79,27)];
[p fill];
NSMutableParagraphStyle* para = [NSMutableParagraphStyle new];
para.alignment = NSTextAlignmentCenter;
NSAttributedString* att =
    [[NSAttributedString alloc] initWithString:@"YES" attributes:
        @{
            NSFontAttributeName:[UIFont fontWithName:@"GillSans-Bold" size:16],
            NSForegroundColorAttributeName:[UIColor whiteColor],
            NSParagraphStyleAttributeName:para
        }];
[att drawInRect:CGRectMake(0,5,79,22)];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.sw2.onImage = im;

看起来像这样:

【讨论】:

  • 来自IOS6编程CookBook,第113页
  • 是的,@giuseppe,他们在 iOS 7 中再次取消了这个功能!所以该代码是 iOS 6 only。这真是令人气愤。
  • 是的,这在 iOS 7 中不起作用,所以不要浪费时间将 UISwitch 外观更改为另一个图像的外观。老实说,这很糟糕..
【解决方案2】:

Apple 没有 UISwitch 的外观 API。您可以设置色调颜色属性 (onTintColor)。但这不是你想要的,我猜。自定义 UISwitch 的问题在于 Apple 可能会拒绝您的应用程序。

但是有一些用于自定义开关的 API,例如 RCSwitch(https://github.com/robertchin/rcswitch) 或 TTSwitch。一个很好的教程和如何使用RCSwitch 的例子可以在这里找到:http://www.raywenderlich.com/23424/photoshop-for-developers-creating-a-custom-uiswitch

【讨论】:

  • 对不起,我忘记了。但它仅适用于 iOS 6。使用这些库将使其与旧版本兼容。
  • 谢谢,您的好意。无论如何,我的项目中不需要旧版本
  • 看来您也想更改拇指外观?如果我错了,请纠正我。
  • 是的,正如我的书所说,拇指必须包含在自定义图像中
猜你喜欢
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多