UIButton selector doesn't work in nested UIVie

2019-08-03 19:09发布

问题:

I have this problem driving me crazy. I have spent decades to figure it out why this is happening.

I have a UIScrollView as scrollView in a UIView. In this scrollView, i have three different UIViews which are created at runtime. In one of these three UIViews, i create a button .Here is my code to do that.

        UIButton *buttonLike = [UIButton buttonWithType:UIButtonTypeRoundedRect ] ;
        buttonLike.frame =CGRectMake(scrollViewWidth +200, 30,36, 16);
        buttonLike.imageView.image = [UIImage imageNamed:@"like.png"];
        [buttonLike addTarget:self action:@selector(buttonLikePressed:) forControlEvents:UIControlEventTouchUpInside] ;

scrollViewWidth is a constant defined and initialized as well.
And,i add this buttonLike as a subview in one of the UIViews. But,no matter what i do , buttonLikePressed method doesn't invoke. I've searched this issue and came up with these solutions.

Iphone UIButton not working in nested UIViews
iPhone SDK 2: UIButton not working in nested views loaded from nib file

They described the same issue. But,as a solution they initialize their views using
-(id)initWithFrame:(CGRect)aRect method. Well,i've already initialized my UIViews using initWithFramemethod. Do u guys have any idea how i can resolve this problem ?

Thank you all

回答1:

Does your button even react to a touch? Does it highlight when pressed?

Because it sounds like you are adding this button to a view outside of that view's bounds which prevents touches being propagated to the button. You either have to increase that view's width to scrollViewWidth + 200 + 36or more or you need to put the button inside view's bounds. Show us how you create that view that you add a button to.



回答2:

You should init all these views with initWithFrame and you should pass in valid frame rects. Try this and you like button will work !



回答3:

I think that the UIButton should get the touch event first but I had a similar issue where the buttons weren't getting pressed. What I ended up doing was running a check in the touchesBegan method of the parent view to see if it touched around the area of the button. This was also very helpful in my case because I was able to specify a larger area so the buttons were easier to press. Then I just fired off the touch event for the button.

Another way which would be much easier would be setting isUserInteractionEnabled to false for the parent views of the button, of course only if you dont need them to respond to touches.

These are just ideas to hack around your problem, not sure how to actually solve it.