简体   繁体   中英

Recognize touches using touches began on any superview

I have created a custom view that contains a UITextField

在此处输入图像描述

I've made the delegate for the UITextView the custom view, in order to encapsulate behaviours about the view to its own file. 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.


I don't know how to assign the delegate to the view controller. I've tried newPostTextView.delegate = self.superview() but this attaches it to the superview and not the view 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. It encapsulates things a little better IMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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