简体   繁体   中英

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.

(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];
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM