22

关闭时看起来像这样:

在此处输入图像描述

虽然我更喜欢灰色背景。我真的必须使用 UIImageView 吗?

4

6 回答 6

53

这是我更改 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。

希望这对某人有帮助:)

于 2013-11-18T03:41:26.943 回答
17

您可以将您的setOnTintColor属性设置为您UISwitch想要的颜色。

于 2013-12-03T12:45:55.727 回答
6

您也可以在 Interface Builder 中为开关设置此项。只需将背景颜色设置为UISwitch您想要的任何颜色(白色,在下面的示例中),然后设置用户定义的运行时属性layer.cornerRadius = 16

在此处输入图像描述

于 2015-06-03T09:53:01.247 回答
4

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.

于 2013-10-04T18:22:10.613 回答
3

您还可以使用图像作为背景,使用 [UIColor colorWithPatternImage];

mySwitch.onTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-on"]];
mySwitch.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-off"]];
于 2014-03-14T13:09:17.183 回答
1

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];
于 2014-07-16T19:49:22.053 回答