简体   繁体   English

使用在任何超级视图上开始的触摸识别触摸

[英]Recognize touches using touches began on any superview

I have created a custom view that contains a UITextField我创建了一个包含 UITextField 的自定义视图

在此处输入图像描述

I've made the delegate for the UITextView the custom view, in order to encapsulate behaviours about the view to its own file.我已将 UITextView 的委托设置为自定义视图,以便将有关视图的行为封装到它自己的文件中。 I then use touches began to close the keyboard when someone touches the screen然后当有人触摸屏幕时,我使用触摸开始关闭键盘

@IBDesignable
class NewPostView:UIView {

    @IBOutlet weak var newPostTextView: UITextView!

    func setup() {
    ...
        newPostTextView.delegate = self
    }
...

    /* Closes the keyboard when somewhere else on the screen is touched */
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
        closeKeyboard()
    }

This only closes the keyboard when the view is custom view is touched however.但是,这仅在触摸自定义视图时关闭键盘。 I'm wondering what the best way to go about closing the text field would be when the screen is touched anywhere, considering that I would still like to encapsulate the custom view as much as possible.我想知道 go 关于关闭文本字段的最佳方法是当屏幕被触摸到任何地方时,考虑到我仍然想尽可能地封装自定义视图。


I don't know how to assign the delegate to the view controller.我不知道如何将委托分配给视图 controller。 I've tried newPostTextView.delegate = self.superview() but this attaches it to the superview and not the view controller我试过newPostTextView.delegate = self.superview()但这将它附加到超级视图而不是视图 controller

The view only intercepts touches in its area.视图仅截取其区域内的触摸。

You need to either setup the touchesBegan on the parent view (or the view that covers the screen space in question), or I'd suggest using a tapGestureRecognizer.您需要在父视图(或覆盖相关屏幕空间的视图)上设置 touchesBegan,或者我建议使用 tapGestureRecognizer。 It encapsulates things a little better IMO.它封装了一些更好的IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM