我有两个按钮,一个带标签0,另一个带标签12,还有一个NSMutableString按钮。 我想要下一个:如果选择了其中一个按钮,或者两个都被选中,我将字符串中的第一个数字设置为1。 如果两者都没有被选中,我将其设置为0.
我的代码是下一个:
- (IBAction)buttonPressed:(UIButton *)button {
button.selected = !button.selected;
if ((button.tag==0 && button.selected) || (button.tag==12 && button.selected))
{
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"1"];
}
else if ((button.tag==0 && !button.selected) && (button.tag==12 && !button.selected))
{
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"0"];
}
}
它不起作用。这有什么不对? 谢谢!
答案 0 :(得分:1)
它不起作用,因为只需按一下按钮就会通知您。例如,如果您按下标签为0的按钮,则将使用按钮0作为参数调用buttonPressed:
方法。您正在测试if表达式中是否选中了两次按钮:button.selected
。但这两次都会检查最近按下的按钮。
if((button.tag == 0&& button.selected)||(button.tag == 12&& button.selected))
你必须独立测试每个按钮状态...... 例如,您可以创建两个存储指针到按钮的出口变量。将它放在视图控制器头文件中:
@property (weak, nonatomic) IBOutlet UIButton *button0;
@property (weak, nonatomic) IBOutlet UIButton *button12;
然后使用布局设计器将您的插座连接到这些按钮。之后你可以获得其中任何一个的.selected属性。
- (IBAction)buttonPressed:(UIButton *)button {
button.selected = !button.selected; // i'm not sure of this line
if ((button.tag==0 || button.tag==12)
{
if( button0.selected || button12.selected )
{ // one of them is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"1"];
} else { // none is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"0"];
}
}
}
或者,如果您想避开这些商店,请查看this question。您可以通过其标记获取视图,例如一些UIButton。如果视图控制器中有视图属性,则可以编写如下内容:
- (IBAction)buttonPressed:(UIButton *)button {
button.selected = !button.selected; // i'm not sure of this line
if ((button.tag==0 || button.tag==12)
{
UIButton *button0 = (UIButton *)[self.view viewWithTag:0];
UIButton *button12 = (UIButton *)[self.view viewWithTag:12];
if( button0.selected || button12.selected )
{ // one of them is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"1"];
} else { // none is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"0"];
}
}
}
答案 1 :(得分:1)
再次检查您的代码。
else if ((button.tag==0 && !button.selected) && (button.tag==12 && !button.selected))
它检查condion button.tag为0和12,所以为此你必须让你的对象都是按钮。
或
试试这个
- (IBAction)buttonPressed:(UIButton *)button
{
button.selected = !button.selected;
if (button.tag==0 || button.tag==12)
{
UIButton *firstBtn = (UIButton *)[button viewWithTag:0];
UIButton *secondBtn = (UIButton *)[button viewWithTag:12];
if( firstBtn.selected || secondBtn.selected )
{ // one of them is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"1"];
} else { // none is selected
NSRange range = {0,1};
[buttonPressings replaceCharactersInRange:range withString:@"0"];
}
}
}