代码:
let switchTerms = UISwitch(frame:CGRectMake(XPos, YPos, Width, Height))
switchTerms.addTarget(self, action: "switchTermsAction:", forControlEvents: .ValueChanged)
switchTerms.onImage = UIImage(named:"SIGN-UP-toggle-Active.png")
scrollSignUp!.addSubview(switchTerms);
func switchTermsAction(sender:UISwitch){
if sender.on{
sender.onImage = UIImage(named:"SIGN-UP-toggle-Active.png")
}
else{
sender.offImage = UIImage(named:"SIGN-UP-toggle-DeActive.png")
}
}
我试图更改UISwitch的背景图像。 似乎未设置背景图像。
我的代码出了什么问题?
答案 0 :(得分:3)
@property (weak, nonatomic) IBOutlet UIImageView *genderSwitchBackgroundImageView;
@property (weak, nonatomic) IBOutlet UISwitch *genderSwitch;
...
- (void)viewDidLoad {
[super viewDidLoad];
self.genderSwitch.onTintColor = [UIColor clearColor];
self.genderSwitch.tintColor = [UIColor clearColor];
[self genderSwitchValueChanged];
}
- (IBAction)genderSwitchValueChanged {
self.genderSwitchBackgroundImageView.image = [UIImage imageNamed:(self.genderSwitch.isOn ? @"toggle_male" : @"toggle_female")];
}
夫特:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var genderSwitchBackgroundImageView: UIImageView!
@IBOutlet weak var genderSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
genderSwitch.tintColor = UIColor.clearColor()
genderSwitch.onTintColor = UIColor.clearColor()
genderSwitchValueChanged()
}
@IBAction func genderSwitchValueChanged() {
genderSwitchBackgroundImageView.image = UIImage(named:genderSwitch.on ? "toggle_male" : "toggle_female")
}
}
答案 1 :(得分:2)
onImage
和offImage
属性自iOS7起无效
尝试创建UIButton,并根据selected:Bool
属性在此按钮上设置图像,使其行为类似于Switch
按下按钮时,请sender.selected = !sender.selected
然后刷新图像。你将有一个自定义开关!