Creating a UISwitch Programmatically

前端 未结 2 1339
鱼传尺愫
鱼传尺愫 2020-12-29 03:07

In a seemingly never ending effort to learn more about iphone development, I have been playing around with some of the source code available through apples developer website

相关标签:
2条回答
  • 2020-12-29 03:44

    The compiler is trying to help you out. You're overriding the onoff instance variable in your viewDidLoad; thus, that's never getting set. In your -flip: method, you're referencing a nil controller. There are two ways to fix this:

    (a) Get rid of the local declaration of onoff, and just use your instance variable

    (b) Cast the sender argument to -flip: as a UISwitch, and access that:

    - (IBAction) flip: (id) sender {
        UISwitch *onoff = (UISwitch *) sender;
        NSLog(@"%@", onoff.on ? @"On" : @"Off");
    }
    
    0 讨论(0)
  • 2020-12-29 03:46

    Steve, I'm sorry if I misunderstood your question. Did you actually create the UISwitch and add it to the view hierarchy? Your controller's -loadView or -viewDidLoad implementation should have code like the following:

    // Use the ivar here
    onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
    [onoff addTarget: self action: @selector(flip:) forControlEvents: UIControlEventValueChanged];
    // Set the desired frame location of onoff here
    [self.view addSubview: onoff];
    [onoff release];
    
    0 讨论(0)
提交回复
热议问题