关闭时看起来像这样:
虽然我更喜欢灰色背景。我真的必须使用 UIImageView 吗?
这是我更改 iOS7 UISwitch 的填充颜色的方法。
首先你需要导入 QuartzCore。
#import <QuartzCore/QuartzCore.h>
然后设置背景颜色并圆化 UISwitch 的角。
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0, 0.0, 51.0, 31.0)];
mySwitch.backgroundColor = [UIColor redColor];
mySwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this.
[self addSubview:mySwitch];
这将为您提供具有自定义关闭(背景)颜色的 UISwitch。
希望这对某人有帮助:)
您可以将您的setOnTintColor
属性设置为您UISwitch
想要的颜色。
您也可以在 Interface Builder 中为开关设置此项。只需将背景颜色设置为UISwitch
您想要的任何颜色(白色,在下面的示例中),然后设置用户定义的运行时属性layer.cornerRadius = 16
:
There's no API support for changing the off fill color of a UISwitch
.
Adjusting the tintColor
will only affect the outline, and adjusting the backgroundColor
will affect the whole frame, including the parts outside the rounded bounds.
You either have to place a properly shaped opaque UIView
behind it or - easier - use a custom open source implementation, such as MBSwitch, which allows you to set the off fill color.
您还可以使用图像作为背景,使用 [UIColor colorWithPatternImage];
mySwitch.onTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-on"]];
mySwitch.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-off"]];
Adding to Barry Wyckoff solution : set tint color also
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0, 0.0, 51.0, 31.0)];
mySwitch.backgroundColor = [UIColor redColor];
mySwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this.
mySwitch.tintColor = [UIColor redColor];
[self addSubview:mySwitch];