removeFromSuperview doesn't work

2019-04-05 11:08发布

I need to be able to remove a button from a view and add a different one. My code looks like this:

-(void)UpdatePromoBanner:(NSString*)value{
    [button setTitle:@"newer text" forState:UIControlStateNormal];
    for (UIView *subView in emptyViewController.view.subviews)
    {
        if(subView.tag == 99) {
            //--remove button and add an updated one
            NSLog(@"Remove button?");
            [subView removeFromSuperview];
            //[subView.superview addSubview:button];
        }
    }
    NSLog(@"event called");

}

-(void)AddPromoBannerToBottom:(UIView*)view {

    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchDown];
    [button setTitle:lblForBannerButton forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    button.tag = 99;

    [view addSubview:button];
}

The emptyViewController is just a plain empty view controller. I'm adding a button in the middle. I hit the NSLog ok that checks the tag, but the view does not get removed. I should mention I'm using a thread thats firing the updatepromobanner every 5 secs.

3条回答
戒情不戒烟
2楼-- · 2019-04-05 11:39

You cannot update the UI using a secondary thread, whenever your thread is doing UI updates you must call the main thread.

查看更多
聊天终结者
3楼-- · 2019-04-05 11:45

Oscar is right. You have to update the interface on the main thread. Figured I'd add in some code to help.

Replace:

[subView removeFromSuperview];

With:

[subView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];

And I think you should be good to go without changing anything else.

查看更多
贼婆χ
4楼-- · 2019-04-05 12:02
dispatch_async(dispatch_get_main_queue(), ^{
         [subView removeFromSuperview];
});

Remember update UI in main thread :)

查看更多
登录 后发表回答