touchesBegan in UIView not being called

2019-04-27 06:59发布

I know that this question must be answered a lot of times already, but it is really giving me a headache right now.

The touchesBegan: is not being called in my UIView. Before I added it in my app, I made a trial project first. In the trial project, everything worked perfectly. What I did was subclass a UIView where the touchesBegan: is being implemented, and add this UIView as a subview of another view. This second view has a button which shows the subclassed UIView once clicked. Again, everything works exactly how I want it to.

Now, when I did the same thing in my existing app, the touchesBegan: method (as well as the touchesMoved:) is never called. Can anyone explain to me why? I just don't really understand why it was never called.

3条回答
Luminary・发光体
2楼-- · 2019-04-27 07:39

In my case background = UIColor.clearColor() was the reason why touchesBegan was not called. Its obviously not called on transparent elements.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-27 07:54

I just found the answer to this. I forgot to mention that the view is inside another UIView, which the userInteraction is disabled (It is disabled by default). So when I enabled the userInteraction of this view, the touches are now being recognized.

查看更多
再贱就再见
4楼-- · 2019-04-27 07:55

I was struggling on this problem for a while... and i figure it out. I think that the touchesBegan override function listen on the main view: the first one on the storyboard tree of the ViewController! I would love to post an image of my storyboard to be more clear, but i can't! ;)

Anyway, IF you have subviews, they may covers the main view... in this manner the touch wont "reach" the main view.

To avoid this you'll have to set the Background property in the Attribute Inspector to Default for ALL THE SUBVIEWS. In this way the background will be transparent and the touch will be able to reach the main view.

If you don't want to set the background to transparent there is something you can do:

-Add an outlet of your last view (with background set)

-Add a tap gesture recognizer to it

-Handle the tap disposing the keyboard

ES.

In properties:

//The last view's outlet
@IBOutlet weak var ContainerView: UIView!

In viewDidLoad():

let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
self.ContainerView.addGestureRecognizer(tap)

Outside:

func handleTap(recognizer: UITapGestureRecognizer){
    self.view.endEditing(true)
}
查看更多
登录 后发表回答