【问题标题】:How can I remove a UIView by the user tapping or swiping anywhere else?如何通过用户在其他任何地方点击或滑动来删除 UIView?
【发布时间】:2023-03-30 10:02:01
【问题描述】:

我在UIView 中为 iPhone 创建了一个迷你弹出菜单,我希望用户能够在他们执行任何操作时关闭视图,而不是选择其中一个选项。因此,如果用户点击/滑动/捏住屏幕上的任何其他元素,弹出视图应该会消失。

但是,我不想检测会阻止其他事情发生的手势...例如,下面有一个 UITableView,如果我向上或向下滑动它,我希望它移动为预计以及会关闭迷你弹出视图。

我应该使用多个手势识别器,还是应该使用 touchesBegan,或者有更好的方法吗?

【问题讨论】:

标签: ios objective-c uiview uigesturerecognizer touches


【解决方案1】:

把这个放在你的UIViewController

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if (touch.view!=yourView && yourView) {
        [yourView removeFromSuperview];
        yourView=nil;
    }

}

编辑:仅在视图存在时才检测触摸和移除的更改

EDIT2:您可以将以下内容添加到您的 UIButtons/UITableView 方法中

 if (yourView) {
     [yourView removeFromSuperview];
     yourView=nil;
    }  

或将 touchesBegan:withEvent: 作为 touchDown 事件添加到您的按钮。

这很烦人,但看不到其他方法,因为 touchesBegan 方法不会被交互式元素调用。

EDIT3:正确的废话,认为我已经搞定了

在您的界面中添加UIGestureRecognizerDelegate

@interface ViewController : UIViewController <UIGestureRecognizerDelegate> {

然后在你的viewDidLoad 添加这个

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod)];
tapped.delegate=self;
tapped.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapped];

然后在你的 viewController 中添加这两个方法

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (touch.view!=yourView && yourView) {
    return YES;
}
return NO;
}

-(void)tapMethod {
[yourView removeFromSuperview];
yourView=nil;
}

【讨论】:

  • 那么我是否必须将 touchesBegan 方法附加到视图控制器?如果是这样,我想我需要以某种方式检查触摸下的元素?
  • 这是他已经对if (touch.view!=yourView) 所做的事情,然后您可以安全地删除 if 大括号中的 yourView。 touch 包含触摸的位置。然后他询问它是否在视图中,如果不是,您可以将其删除 =)
  • 谢谢 - 但不幸的是,这似乎只适用于没有用户交互的视图控制器区域......在我有 UIButtons 和 UITableViewtouchesBegan:消息似乎没有通过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
相关资源
最近更新 更多