我有一个 UIControl,它实现了 touches started 方法,如下所示:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
//More code goes here
UIControl 的这个子类在视图控制器中实例化,然后作为子视图添加到该视图控制器。我在 UIControl 的 touches started 方法上有一个断点,并且该方法永远不会被调用。我一直在做一些阅读,似乎视图控制器有一些逻辑来决定是否将触摸事件传递给它的子视图。奇怪的是我在同一个视图控制器中有一个不同的 UIControl 子类,当用户触摸它时,触摸事件会传递给它!这是完整的代码:
。H
#import <UIKit/UIKit.h>
@interface CustomSegment : UIView
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, assign) NSInteger segments;
@property (nonatomic, strong) NSArray *touchDownImages;
@property (nonatomic, readonly, assign) NSInteger selectedIndex;
@property (nonatomic, weak) id delegate;
- (id)initWithPoint:(CGPoint)point numberOfSegments:(NSInteger)_segments andTouchDownImages:(NSArray *)_touchDownImages;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@end
.m
#import "CustomSegment.h"
@implementation CustomSegment
@synthesize bgImageView, segments, touchDownImages, selectedIndex, delegate;
- (id)initWithPoint:(CGPoint)point
numberOfSegments:(NSInteger)_segments
andTouchDownImages:(NSArray *)_touchDownImages
{
self = [super initWithFrame:CGRectMake(point.x, point.y, [[_touchDownImages objectAtIndex:0] size].width, [[touchDownImages objectAtIndex:0] size].height)];
if (self)
{
touchDownImages = _touchDownImages;
segments = _segments;
bgImageView = [[UIImageView alloc] initWithImage:[touchDownImages objectAtIndex:0]];
[self addSubview:bgImageView];
}
return self;
}
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
float widthOfSegment = [self frame].size.width / segments;
float bottomPoint = 0;
float topPoint = widthOfSegment;
for (int i = 0; i < segments; i++)
{
if ([touch locationInView:self].x > bottomPoint && [touch locationInView:self].x < topPoint)
{
[bgImageView setImage:[touchDownImages objectAtIndex:i]];
selectedIndex = i;
return;
}
else
{
bottomPoint = topPoint;
topPoint += topPoint;
}
}
}
@end