我使用了 andrej 的基于 UISegmentedControl 的方法,并对其进行了扩展,使其表现得更像一个普通的 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
对于基本用法,您可以将其用作 UIButton 插件替换:
_button = [[SPWKBarButton alloc] initWithTitle:titles[0]];
[_button addTarget:self
action:@selector(doSomething:)
forControlEvents:UIControlEventTouchUpInside];
[self.navigationItem setTitleView:_button];
该事件仅在触摸发生在分段控件的范围内时才会触发。享受。