Search code examples
objective-cuicontrol

UIControl addTarget:action:forControlEvents: not working unless same size as superview


E.g.

UIButton *b = [Uibutton alloc...
[b addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];

// Using Masonry to add constraints:
[b makeConstraints:^(MASConstraintMaker *make) {

  // Match superview - works
  make.top.left.bottom.right.equalTo(superview);

  // Smaller than superview - doesn't work
  make.top.left.right.top.equalTo(superview);
  make.height.equalTo(@32);
}];

Any ideas why?

Only reference to issue I can find is the answer to this question, but it's vague on the details.


Solution

  • I'm not familiar with Masonry MASConstraintMaker but I assume the same happens if you use button.frame? Or that you can't use button.frame for some reason?

    If your button is outside it's superview it won't work.. which leads me to suggest (albeit a bit naively and simplistically) that your button is being set outside of it's superview... potentially because it's using superview.frame and not superview.bounds.. which is what you need to use for superView frame references

    button.frame = CGRectMake(button.superview.bounds.origin.x, button.superview.bounds.origin.y, button.superview.bounds.size.width, 32.0f);