2013-03-19 49 views
0

我在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为)本功能”的,但我这样做时,我无法获得与关联此我的开关**

+0

你的意思是你不能使用开关(不能与它交互)或不能读取正确的值? – M0rph3v5 2013-03-19 14:33:04

+0

我不能读它,实际上如果你看到我的代码在Uiactionsheet当我试图通过switch语句捕获它永远不会返回任何东西:S – 2013-03-19 14:44:25

回答

1

下面的代码将有助于

switchButton = [[UISwitch alloc] init]; 

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

啊,先生,非常感谢你:)。 – 2013-03-19 14:49:02

+1

当使用[switch isOn]/on属性时,您应该能够从开关读取输入正常值。你的代码可能有其他问题,是否有任何机会(在阅读时)切换到零? – M0rph3v5 2013-03-19 16:01:17

0

将它设置为IBOutlet将不会执行任何操作,因为您正在以编程方式创建开关。真的,你应该创建你自己的UIViewController(并在Interface Builder中设计它),而不是使用设计用于简单按钮选择的UIActionSheet。

但是,如果您确实继续使用UIActionSheet,则可以在创建UISwitch时调用“addTarget”以在交换机发生更改时捕获事件。

+0

所以我应该去自定义视图? – 2013-03-19 14:45:26

0

此外,你可以为UISwitch视图设置变量值(6例如),添加子视图的UIActionSheet之前。然后,当方法clickedButtonAtIndex烧制用[(UISwitch *)[actionSheet viewWithTag:6] isChecked]

0

你可以检查它的价值你可以有哪些可以为UISwitch

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

设置的值在ActionSheet布尔标志,你可以检查标志swithcOn