views:

204

answers:

1

I'm trying to add a UIButton to a UIView, but am having some trouble with getting it to respond to touches.

I have a method which returns UIButtons after I provide it with a tag:

- (UIButton*)niceSizeButtonWithTag:(int)tag {

    UIButton * aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [aButton setTag:tag];
    [aButton addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];

    CGRect newFrame = aButton.frame;
    newFrame.size.width = 44;
    newFrame.size.height = 44;
    [aButton setFrame:newFrame];

    return aButton;
}

As you can see I'm creating a new button and increasing the size. I use this in the following way:

UIButton * anotherButton = [self niceSizeButtonWithTag:1];
[anotherButton setImage:[UIImage imageNamed:@"image" withExtension:@"png"] forState:UIControlStateNormal];
[anotherButton setCenter:CGPointMake(middleOfView)];
[aView addSubview:anotherButton];

I create a lot of buttons like this, hence the reason for the method.

The buttons are always created and added to the subview perfectly. I can see the image and they're in the correct position. The problem is that they only respond to touches in a tiny strip.

In this attached image,

alt text

  • The yellow shows the whole frame of the button,
  • The red shows the area that will respond to touches.
  • The grey shows a section of the view the button is added to.

If anyone could shed some light on why this is happening, it would be really useful.

UPDATE:

I should probably mention I'm trying to add this button to a UIView which is a subview of a UITableViewCell.

UPDATE 2:

Adding it directly to the UITableViewCell works, adding it to the UIView on the UITableViewCell is causing the error.

FINAL UPDATE The problem turned out to be that I was sending the view containing the button to the back of the subviews on the UITableViewCell. Getting rid of the sendSubviewToBack: call fixed it.

+1  A: 

Do you have any other views added to this containing view after you add the button? try setting some of your view's background color to blueColor, redColor and other colors to better see what the stack of views in your app is like. Then you should be easily able to see if there is some sort of view blocking the button.

coneybeare
I'm only ever adding more buttons, and they never overlap. Also, the problem is still there if the UIButton is the only subview I add.
Tom Irving
Perhaps you could post all of your code. From the original picture (the img src is now broken) it definitely appears to have the symptoms of a view above it blocking touch events from getting lower. If you posted something, other people could see what was going on and maybe something you are missing. With the code you have here, it all looks correct.
coneybeare
Exactly, and this is all my code :)
Tom Irving
Turns out I was sending the containing view to the back, removing that line did it. Thanks a lot.
Tom Irving