Pergunta

I have a very simple Objective-J webapp that is a label and a button. The label text changes when the button is pressed. I want to make the title of the button change as well. If I put the change statement in the swap function below (function that runs when the button is pressed) then the webapp does not launch properly.

How can I modify this code so that the button reads Tommy Arrives when the label text is Good Bye Tommy?

@import <Foundation/CPObject.j>


@implementation AppController : CPObject
{
    CPTextField label;
    CPButton button;
}

// Launches UI in the App
- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
    var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask],contentView = [theWindow contentView];

label = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];

[label setStringValue:@"Hello Tommy Jones!"];
[label setFont:[CPFont boldSystemFontOfSize:24.0]];

[label sizeToFit];

[label setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin];
[label setCenter:[contentView center]];

[contentView addSubview:label];
[label setAlignment:CPCenterTextAlignment]; 

button = [[CPButton alloc] initWithFrame: CGRectMake( CGRectGetWidth([contentView bounds])/2.0 - 50, CGRectGetMaxY([label frame]) + 10, 100, 24 )]; 

[button setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin];
[button setTitle:"Tommy Leaves"];
[button setTarget:self];
[button setAction:@selector(swap:)];
[contentView addSubview:button];

[theWindow orderFront:self];

// Uncomment the following line to turn on the standard menu bar.
[CPMenu setMenuBarVisible:YES];
}


// Executes when button is pressed
- (void)swap:(id)sender 
{ 
    if
    ([label stringValue] == "Hello Tommy Jones!") [label setStringValue:"Good Bye Tommy!"];
    // [button setTitle:"Tommy Leaves"];
    // [contentView addSubview:button];

        else
    [label setStringValue:"Hello Tommy Jones!"];
    // [button setTitle:"Tommy Arrives"];
}  

@end
Foi útil?

Solução

Looks like you're missing some braces. An if statement, or its else clause, only takes a single 'command' unless you wrap the lot in {}. E.g.

if ([label stringValue] == "Hello Tommy Jones!") 
{
    [label setStringValue:"Good Bye Tommy!"];
    [button setTitle:"Tommy Leaves"];
}
else
{
    [label setStringValue:"Hello Tommy Jones!"];
    [button setTitle:"Tommy Arrives"];
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top