XCode 创建一个按钮切换,显示一个图像打开和一个关闭功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16676951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XCode Create a Button Toggle that shows one image for On and one for Off with function
提问by Ryan Watts
I am trying to create a toggle button in XCode that is an On and Off switch for toggling incoming text messages. When the feature is on the image is designed to say ON. I need to set this image property for the state that the button is on. When the image is off. The button has an image that says Off.
我正在尝试在 XCode 中创建一个切换按钮,它是一个用于切换传入文本消息的 On 和 Off 开关。当该功能出现在图像上时,它被设计为开启。我需要为按钮打开的状态设置这个图像属性。当图像关闭时。该按钮有一个显示关闭的图像。
What is the best route to complete this code.
完成此代码的最佳途径是什么。
Ryan
瑞安
回答by Ernesto Garza-Aldape
I use:
我用:
//Create a Switch
UISwitch *myswitchbutton;
myswitchbutton.frame=CGRectMake(10, 10, 40, 50);
[self addsubview:myswitchbutton];
Then, add images
然后,添加图像
myswitchbutton.offImage=[UIImage imageNamed:@"off.png"];
myswitchbutton.onImage=[UIImage imageNamed:@"on.png"];
Where off.png and on.png are images with your custom design
off.png 和 on.png 是您自定义设计的图像
回答by Nishant Tyagi
You can add UISwitch for this :
您可以为此添加 UISwitch:
So there can be two ways for this :
所以可以有两种方法:
(1). Create a UISwitch object and then add it like this :
(1). 创建一个 UISwitch 对象,然后像这样添加它:
UISwitch *onoff = [[UISwitch alloc] initWithFrame: CGRectMake(x_value,y_value,79,27)];
[onoff addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview: onoff];
// This is the method called when switch state changes
// 这是switch状态改变时调用的方法
- (IBAction) flip: (id) sender
{
UISwitch *onoff = (UISwitch *) sender;
if(onoff.on)
{
// switch is on
}
else
{
// switch is off
}
}
(2). Drag UISwitch using interface builder onto your view and connects its outlet and add target for switch events.
(2). 使用界面构建器将 UISwitch 拖到您的视图上并连接其插座并为开关事件添加目标。
The on/off images for a UISwitch can be customized using the onImage and offImage properties as described here.
可以使用此处所述的 onImage 和 offImage 属性自定义 UISwitch 的开/关图像。
There are many sample codes which can be used for custom switch :
有许多示例代码可用于自定义开关:
1.simpleswitch2. rcswitch3.DCRoundSwitch
1. simpleswitch2. rcswitch3. DCRoundSwitch
Hope it helps you.
希望对你有帮助。