5

我想从 uiwindow 中删除一个视图,所以我在 appdelegate 方法中使用 nslog,它说窗口的子视图计为两个NSLog(@" %d",[[self.window subviews] count]);,所以我如何从窗口中删除该子视图,如果我删除该子视图,我有标签栏控制器要继续...

- (void) GetUserCompleted

{
    NSLog(@"   %@",[[self.window subviews] objectAtIndex:0]);   
    NSLog(@"   %@",[[self.window subviews] objectAtIndex:1]); 
}
4

3 回答 3

15

您可以使用以下代码删除单个子视图。

[subview_Name removeFromSuperview];

如果要从视图中删除所有子视图,请使用它。

NSArray *subViewArray = [self.window subviews];
for (id obj in subViewArray)
{
    [obj removeFromSuperview];
}
于 2013-02-21T08:12:35.063 回答
10

希望下面的代码对删除特定视图有用

   Set tag for that remove view

   subview.tag = 1;

   then

   [[[self window] viewWithTag:1] removeFromSuperview];
于 2014-04-01T05:56:04.637 回答
10

@Maddy 答案的 Swift 版本:

//create view then add a tag to it. The tag references the view
var myNewView = UIView()
myNewView.tag = 100

//add the  view you just created to the window
window.addSubview(myNewView)

//remove the view you just created from the window. Use the same tag reference
window.viewWithTag(100)?.removeFromSuperview

更新

这是另一种在不使用窗口标签的情况下删除 UIView 的方法。关键是视图必须是实例属性。

lazy var myNewView: UIView = {
    let view = UIView()
    return view
}()

viewDidLoad() {

    guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }

    window.addsubView(myNewView)
}

// call this in deinit or wherever you want to remove myNewView
func removeViewFromWindow() {

    guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }

    if myNewView.isDescendant(of: window) {
        print("myNewView isDescendant of window")
    }

    for view in window.subviews as [UIView] where view == myNewView {
        view.removeFromSuperview()
        break
    }

    if myNewView.isDescendant(of: window) {
        print("myNewView isDescendant of window")
    } else {
        print("myNewView is REMOVED from window") // THIS WILL PRINT
    }
}

deinit() {
    removeViewFromWindow()
}
于 2017-08-05T22:00:12.770 回答