【问题标题】:removeFromSuperview doesn't workremoveFromSuperview 不起作用
【发布时间】:2012-08-13 20:53:59
【问题描述】:

我需要能够从视图中删除一个按钮并添加一个不同的按钮。我的代码如下所示:

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

emptyViewController 只是一个普通的空视图控制器。我在中间添加一个按钮。我点击了检查标签的 NSLog ok,但视图没有被删除。我应该提到我正在使用每 5 秒触发一次 updatepromobanner 的线程。

【问题讨论】:

  • 请以小写字母开头。

标签: iphone objective-c xcode uiview


【解决方案1】:

您无法使用辅助线程更新 UI,每当您的线程进行 UI 更新时,您必须调用主线程。

【讨论】:

    【解决方案2】:

    奥斯卡是对的。您必须更新主线程上的界面。想我会添加一些代码来帮助。

    替换:

    [subView removeFromSuperview];
    

    与:

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

    而且我认为你应该很好地去而不改变任何其他东西。

    【讨论】:

    • 已经把我逼疯了好几个小时。谢谢!
    • 很高兴为您提供帮助。快乐编码:)
    • 嘿@RyanPoolos,想知道如果我想取出一个单独的视图控制器而不是一个按钮怎么办?每当我删除它时,它都会引发错误。如果你有时间,这里是我几个小时前发布的一个问题。 stackoverflow.com/questions/15490656/… 谢谢!
    • Apple 在文档中警告要从视图的 drawRect: 方法调用它(这似乎很明显)似乎很奇怪,但不要提及这一点。
    【解决方案3】:
    dispatch_async(dispatch_get_main_queue(), ^{
             [subView removeFromSuperview];
    });
    

    记得在主线程中更新 UI :)

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      相关资源
      最近更新 更多