UISwitch设置开/关图像

Yun*_* Su 8 xcode uiswitch swift

我想像我这样设置我的Switch:

在此输入图像描述

但我尝试在ios9中,它不起作用.我在苹果UISwitch Class Reference中看到过.它说:

讨论在iOS 7中,此属性无效.

iOS 9怎么样?任何一个成功?

我的代码:

switch1 = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
switch1.on = true
switch1.onTintColor = UIColor.lightGrayColor()
switch1.tintColor = UIColor.greenColor()
switch1.thumbTintColor = UIColor.blackColor()
Run Code Online (Sandbox Code Playgroud)

//设置开/关图像

switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")
Run Code Online (Sandbox Code Playgroud)

rob*_*off 20

UIButton改用.

let switchButton = UIButton(type: .Custom)
switchButton.selected = true
switchButton.setImage(UIImage(named: "on-switch"), forState: .Selected)
switchButton.setImage(UIImage(named: "off-switch"), forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

switchButton.selected而不是switch1.on.switchButton.selected点击它时你必须切换(switchButton.selected = !switchButton.selected).