无法从超级视图中删除子视图

时间:2015-08-12 10:00:13

标签: ios objective-c uiview

当我触摸subview以“屏蔽”应用的其余部分时,我添加searchBar。然后,当我触摸它时,我想删除此视图。但没有任何反应。有人可以向我解释一下吗?

这是我的代码:

@property (nonatomic) UIView *blackView;

- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar {
    NSLog(@"Touched in searchbar");
    UIView* blackView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    blackView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];

    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeKeyboard:)];
    [self.view addGestureRecognizer:singleFingerTap];

    [self.view addSubview:blackView];

    return YES;
}

-(void)removeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.searchBar resignFirstResponder];
    [self.blackView removeFromSuperview];
}

谢谢。

4 个答案:

答案 0 :(得分:1)

你在做什么

[self.blackView removeFromSuperview];

哪个好。但是我没有看到你把它放在任何地方。在创建黑色视图后执行此操作。

[self setBlackView:blackView]

答案 1 :(得分:0)

在函数searchBarShouldBeginEditin中创建新变量backView:

UIView* blackView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

在这种情况下,self.blackView不是这个UIView

在界面中定义UIView * blackView,如下所示

@iterface Controller {
     UIView *blackView;
}

然后创建黑色视图:

- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar {
    blackView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    blackView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];

    ....
    return YES;
}

现在删除它:

-(void)removeKeyboard:(UITapGestureRecognizer *)recognizer {
    ...

    [blackView removeFromSuperview];
}

答案 2 :(得分:0)

我的坏。我创建了一个新变量,而不是使用界面中的变量。这里是干净的代码。

@property (nonatomic) UIView *blackView;

- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar {
    NSLog(@"Touched in searchbar");
    self.blackView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.blackView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];

    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeKeyboard:)];
    [self.blackview addGestureRecognizer:singleFingerTap];

    [self.view addSubview:self.blackView];

    return YES;
}

-(void)removeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.searchBar resignFirstResponder];
    [self.blackView removeFromSuperview];
}

答案 3 :(得分:0)

您在 searchBarShouldBeginEditing 功能中本地创建了“blackView”变量,该功能在 removeKeyboard 功能中无法访问。 尝试使用上面声明的属性变量。