如果其他声明不起作用!

2 if-statement objective-c button

此代码中没有错误,但是当我单击按钮时,"if"语句中没有任何内容正常工作!它不会崩溃或显示错误...顺便说一下我在iPhone上的Xcode工作.

#import "MainView.h"

@implementation MainView

@synthesize MyButton2, MyMainTextLabel;
@synthesize MyButton3, MyMainTextLabel;
@synthesize MyButton2, Button2Label;
@synthesize MyButton2, Button3Label;
@synthesize MyButton3, Button2Label;
@synthesize MyButton3, Button3Label;


- (IBAction)Button2click {


    if(Button2Label.text == @"Hello There!") {

        MyMainTextLabel.text = @"\"Hey...!!\"";

        Button3Label.text = @"What a rude Penguin!";
        Button2Label.text = @"Hows a Goin?";
    }

}

- (IBAction)Button3click {

    if(Button3Label.text == @"Penguins SUCK!") {

        MyMainTextLabel.text = @"\"DONT TEST ME!!\"";

        Button3Label.text = @"Oh I Will!";
        Button2Label.text = @"Sorry I didnt mean to...";

    }
}

- (IBAction)buttonclick {

}
@end
Run Code Online (Sandbox Code Playgroud)

Chu*_*uck 19

你无法比较字符串==.只有当它们是完全相同的NSString对象时才会起作用,而不是它们是两个相同的字符串.使用[buttonLabel.text isEqualToString:@"Hello There!"]


Jim*_*eia 8

当你写:

Button2Label.text == @"Hello There!"

您正在测试按钮标签和静态字符串之间的指针相等性.你想从字符串相等测试,而不是指针相等:

if ([Button2Label.text isEqualToString: @"Hello There!") { ... }

也就是说,根据按钮的标签在动作方法中做出运行时决策是一个糟糕的设计,如果按钮的标签因任何原因(包括本地化)发生变化,将会让您遇到麻烦.

关闭发件人或发件人的标签是首选模式.