I used the andrej UISegmentedControl-based approach and expanded it a bit to behave like a regular UIButton:
@interface SPWKBarButton : UISegmentedControl - (id)initWithTitle:(NSString *)title; - (void)setTitle:(NSString *)title; @end @implementation SPWKBarButton - (id)initWithTitle:(NSString *)title { self = [super initWithItems:@[title]]; if (self) { self.segmentedControlStyle = UISegmentedControlStyleBar; NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor]; [self setTitleTextAttributes:attributes forState:UIControlStateNormal]; } return self; } - (void)setTitle:(NSString *)title { [self setTitle:title forSegmentAtIndex:0]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; if (CGRectContainsPoint(self.bounds, [[touches anyObject] locationInView:self])) { self.selectedSegmentIndex = 0; } else { self.selectedSegmentIndex = UISegmentedControlNoSegment; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; if (CGRectContainsPoint(self.bounds, [[touches anyObject] locationInView:self])) { [self sendActionsForControlEvents:UIControlEventTouchUpInside]; } self.selectedSegmentIndex = UISegmentedControlNoSegment; } @end
For basic use, you can use it as a replacement using UIButton:
_button = [[SPWKBarButton alloc] initWithTitle:titles[0]]; [_button addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside]; [self.navigationItem setTitleView:_button];
The event will fire only if the touch occurs within the borders of the segmented control. Enjoy it.
source share