UIButton作为开关 [英] UIButton as switch
问题描述
我正在尝试使用Xcode4 for iOS中的自定义图像创建一个类似按下按钮的按钮。
我正在使用的代码是
I'm trying to create a push-on-push-off-like button with custom images in Xcode4 for iOS. The code I'm using is
- (IBAction)btnAll:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
现在工作正常。
但我的问题是,当我正在切换时,我按下它,然后它再次弹出然后终于打开。
该应用程序有效,但这确实很难看。
That works fine for now. But my problem is, that when I'm toggling on, I press it on, then it is popping off again and then finally on. The app works, but that is really ugly, though.
我首先将突出显示的图像设置为开启。因此,当我突出显示按钮时,它会亮起并弹出。这很好。但当我再次关闭它时,问题是相反的,反方向。
I firstly set the "highlighted" image to on. So when I highlight the button, it is on and that popping to on. That works fine. But when I turn it off again, the problem is the same, in the reverse direction.
我试图把这个代码:
- (IBAction)btnAll:(id)sender
{
UIButton *button = (UIButton *)sender;
if(button.selected)
{
[button setImage[UIImage imageNamed@"off.png"] forState:UIControlStateHighlighted];
}
else
{
[button setImage[UIImage imageNamed@"on.png"] forState:UIControlStateHighlighted];
}
button.selected = !button.selected;
}
但是长 button.selected =!按钮。选中
没有区别。
所以它不会做任何改变。
But as long button.selected = !button.selected
there is no difference.
So it won't make any change.
我也尝试在»触摸下来«触发IBAction但是你可以想象这看起来有多么令人沮丧。
I also tried to trigger the IBAction on »Touch Down« but you can imagine how frustrating this will look like.
有没有人能解决这个问题?
有没有人为那个人而烦恼?
Has anybody got a solution for that problem? Did anybody struggle with that one too?
迎接,非常感谢
Julian
Greets, thanks a lot Julian
推荐答案
之前我遇到过类似的问题,点击时按钮的工作有点奇怪。试试这个代码并让我知道它是否有效
I've had a similar problem to this before, the button works a little strangely when tapping. Try this code and let me know if it works
UIButton *button = (UIButton *)sender;
if(button.selected)
{
[button setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateSelected];
[button setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateHighlighted | UIControlStateSelected];
}
else
{
[button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateSelected];
[button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateHighlighted | UIControlStateSelected];
}
button.selected = !button.selected;
If (button.selected) {
[button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateNormal];
} else {
[button setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateNormal];
}
点击并按住某个按钮时,状态实际上是突出显示的&选择此选项,您需要高光和选定状态的图像。
When you tap and hold on a button the state is actually Highlighted & Selected so you need an image for both Highlight and selected state.
这篇关于UIButton作为开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!