-3

我正在编写一些代码,它将在我的应用程序中写入一条短信,如下所示:

MFMessageComposeViewController *messageComposer = [[MFMessageComposeViewController alloc]  init];
[messageComposer setMessageComposeDelegate:self];
//    Check The Device Can Send Text Messages
if ([MFMessageComposeViewController canSendText]) {
    [messageComposer setRecipients:[NSArray arrayWithObjects: nil]];
    [messageComposer setBody:messageBodyText];
    [self presentViewController:messageComposer animated:YES completion:NULL];
} else {
//        Need to add an alert view
    NSLog(@"TEXT ISNT WORKING");
}

}

所以我目前有一个 if 语句来检查设备是否能够发送消息,但是如何在其中添加另一个 if 语句?我基本上想根据我视图中的开关位置来决定消息正文是什么,例如:

如果开关在左:消息正文为 A
如果开关在右:消息正文为 B

4

2 回答 2

1

这确实是一个开关的主要示例,甚至 Gary 也是这样描述它的:

if ([MFMessageComposeViewController canSendText]) {
    [messageComposer setRecipients:[NSArray arrayWithObjects: nil]]

    //yourSwitchIsRightSide should be bool value
    switch (yourRightSide) {
        case YES:
            [messageComposer setBody:yourRightMessageBodyText];
            break;
        case NO:
            [messageComposer setBody:yourLeftMessageBodyText];
            break;
    }

    [self presentViewController:messageComposer animated:YES completion:NULL];
} else {
    //        Need to add an alert view
}

除了提高可读性开关/案例还可以更好地扩展。如果 Gary 决定稍后他想在 if-else 上有几个额外的选项,那会造成真正的混乱。(在这种情况下,BOOL 可能应该被对枚举的检查所取代)

switch (switchDirection) {
    case MFSwitchDirectionLeft:
        [messageComposer setBody:yourLeftMessageBodyText];
        break;
    case MFSwitchDirectionRight:
        [messageComposer setBody:yourRightMessageBodyText];
        break;
    case MFSwitchDirectionUp:
        [messageComposer setBody:yourUpMessageBodyText];
        break;
    case MFSwitchDirectionDown:
        [messageComposer setBody:yourDownMessageBodyText];
        break;
    default:
        break;
}
于 2013-11-01T21:40:02.617 回答
-1

尝试给定的代码。检查您的开关值是在左侧还是右侧,我认为您的开关变量是 yourSwitchIsRightSide。

MFMessageComposeViewController *messageComposer = [[MFMessageComposeViewController alloc]  init];
[messageComposer setMessageComposeDelegate:self];
//    Check The Device Can Send Text Messages
if ([MFMessageComposeViewController canSendText]) {
    [messageComposer setRecipients:[NSArray arrayWithObjects: nil]]

  //yourSwitchIsRightSide should be bool value
    if(yourSwitchIsRightSide){
        [messageComposer setBody:yourRightMessageBodyText];
    }
    else{
        [messageComposer setBody:yourLeftMessageBodyText];
    }

    [self presentViewController:messageComposer animated:YES completion:NULL];
} else {
//        Need to add an alert view
    NSLog(@"TEXT ISNT WORKING");
}
}
于 2013-11-01T17:14:54.110 回答