UISwitch 设置开/关图像 [英] UISwitch set on/off Image

查看:40
本文介绍了UISwitch 设置开/关图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样设置我的开关:

I want to set my Switch like this:

但是我在 ios9 中尝试,它不起作用.我在苹果 UISwitch 类参考中看到.它说:

But I try in ios9 , it does not work. I saw in apple UISwitch Class Reference. It says that :

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

Discussion In iOS 7, this property has no effect.

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

How about iOS 9? Any one success?

我的代码:

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()

//设置开/关图像

switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")

推荐答案

改用 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)

使用 switchButton.isSelected 而不是 switch1.on.您必须在点击 switchButton.isSelected 时切换它,您可以这样做:

Use switchButton.isSelected instead of switch1.on. You'll have to toggle switchButton.isSelected when it is tapped, which you can do like this:

switchButton.isSelected.toggle()

这篇关于UISwitch 设置开/关图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆