Search code examples
ioscocoa-touchuiswitch

UISwitch won't show up in custom UIView


I made a custom UIView class and trying to set up in it an UISwitch controller programmatically. The UISwitch won't show up. Where's the evil?

UIView class:

- (void)viewWillAppear:(BOOL)animated
{
    uiSwitch=[[[UISwitch alloc]initWithFrame:CGRectMake(5.00,200.00,79,27)] autorelease];
    [uiSwitch addTarget:self action:@selector(uiSwitchCurrentStatus) forControlEvents:UIControlEventValueChanged];
    [self addSubview:uiSwitch];
}

I've checked another issues regarding UIswitch, but all of them seems like not my case. Thank you in advance.


Solution

  • (if inside UIViewCotroller) Try [self.view addSubview:uiSwitch];

    Or if this really inside the UIView class, move the whole method to a view controller.

    Or put the the code in UIView's layoutSubviews.

    And in any case you should check, if the switch already exists. Otherwise it could be leaking.

    Also if placed in view controller- (void)viewDidLoad might be the better place.

    -(void)layoutSubviews{
        if (!uiSwitch){
            uiSwitch=[[[UISwitch alloc]initWithFrame:CGRectMake(5.00,200.00,79,27)] autorelease];
            [uiSwitch addTarget:self action:@selector(uiSwitchCurrentStatus) forControlEvents:UIControlEventValueChanged];
            [self addSubview:uiSwitch];
        }
    
    }