如何从UIactionsheet中的UISwitch获得答案

时间:2013-03-19 14:27:56

标签: ios uiactionsheet uiswitch

我正在我的uiactionsheet中实现Uiswitch,我已成功将它放置在我想要的位置,但无法使用它。这是我的代码:

switchButton = [[UISwitch alloc] init];
[mySheet addSubview:switchButton];
[mySheet showInView:self.view];

UILabel *instruction = [[UILabel alloc] init];
[instruction setBackgroundColor:[UIColor clearColor]];
[instruction setText:@"Daily"];
[mySheet addSubview:instruction];

// get the dimension of the sheet to position the switch
CGSize parentSize  = mySheet.frame.size;
CGRect rect = switchButton.frame;
rect.origin.x = parentSize.width/2.0 - rect.size.width + 90;
rect.origin.y = parentSize.height - rect.size.height + 90 ;
switchButton.frame = rect;


//get the dimension of the sheet to possition the label
rect.origin.x = parentSize.width/2.0 - rect.size.width -20;
rect.origin.y = parentSize.height - rect.size.height + 90 ;
instruction.frame = rect;

我已将我的开关按钮初始化为iboutlet。在动作表的功能中,我正在尝试这样做。

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:        (NSInteger)buttonIndex{



    switch (buttonIndex) {
        case 0:
        {

            NSLog(@"Yes Button is working");
        }
            break;
         case 1:
        {

            if(switchButton.on){

            NSLog(@"IS on ?");
        }
          else {

         NSLog(@"Is off?");

         }
        }
        default:
            break;
    }

It is all set

** IMP我也试过更多的东西,我为它制作了“ - (ibAction)功能”,但是当我这样做时,我无法将它与我的开关联系起来**

4 个答案:

答案 0 :(得分:1)

以下代码将有所帮助

switchButton = [[UISwitch alloc] init];

[switchButton addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

答案 1 :(得分:0)

将其设置为IBOutlet将不会执行任何操作,因为您是以编程方式创建交换机的。真的,您应该创建自己的UIViewController(并在Interface Builder中设计),您可以模态显示,而不是使用专为简单按钮选择而设计的UIActionSheet。

但是,如果您继续使用UIActionSheet,则可以在创建UISwitch时为其调用'addTarget',以便在更改开关时捕获事件。

答案 2 :(得分:0)

在将子视图添加到UIActionSheet之前,您还可以为UISwitch视图设置标记值(例如6)。然后,当方法clickedButtonAtIndex被触发时,您可以使用[(UISwitch *)[actionSheet viewWithTag:6] isChecked]

检查其值

答案 3 :(得分:0)

你可以有一个BOOL标志,可以设置UISwitch

的值
[mySwitch addTarget:self action:@selector(switchChanged) forControlEvents: UIControlEventTouchUpInside];
-(void)switchChanged{
    if(switchOn){
     switchOn=NO;
   }
   else {
     switch=YES;
   }
}

ActionSheet中,您可以查看标记swithcOn

相关问题