Nicos Karalis Nicos Karalis - 3 months ago 14
iOS Question

Custom UIView not receiving touch events

I am building a custom slider to my application.

I found a library on Github as inspiration.

I have created the file:

NKSlider
as a subclass of
UIView
and implemented on it the
drawRect
as the library did and implemented the methods:
touchesMoved:withEvent:
and
touchesBegan:withEvent:
. But none of the touches events are being called.

this is how i add this custom view to my view controller:

NKHandler *nk = [[NKHandler alloc] init];
nk.frame = CGRectMake(20, 20, 280, 36);
[self.view addSubview:nk];
[self.view addSubview:[[NKHandler alloc] initWithFrame:CGRectMake(20, 60, 280, 100)]];


and this are the classes. What am i doing wrong??

the
.h


#import <UIKit/UIKit.h>

@interface NKHandler : UIView

@end


and
.m


#import "NKHandler.h"

static inline CGPoint CGPointTopCenter(CGRect rect) {
CGPoint p; p.x = rect.origin.x + (rect.size.width / 2); p.y = rect.origin.y; return p;
}
static inline CGPoint CGPointBottomCenter(CGRect rect) {
CGPoint p; p.x = rect.origin.x + (rect.size.width / 2); p.y = rect.origin.y + rect.size.height; return p;
}
static inline CGPoint CGPointLeftCenter(CGRect rect) {
CGPoint p; p.x = rect.origin.x; p.y = rect.origin.y + (rect.size.height / 2); return p;
}
static inline CGPoint CGPointRightCenter(CGRect rect) {
CGPoint p; p.x = rect.origin.x + rect.size.width; p.y = rect.origin.y + (rect.size.height / 2); return p;
}

@implementation NKHandler {
int _selectedStep;
}

-(id)init {
self = [super init];
if (self) {
self.backgroundColor = [UIColor clearColor];

self.clipsToBounds = NO;
self.opaque = YES;

_selectedStep = 5;
}
return self;
}

-(void) setStep:(int) step {
_selectedStep = step;
[self setNeedsDisplay];
}

-(void)layoutSubviews {
... layout stuff ...
}
-(void)drawRect:(CGRect)rect {
... Boring drawing stuff ..
}

#pragma mark - Touch Handling

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __PRETTY_FUNCTION__);
[self setStep:(_selectedStep+1)%11];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __PRETTY_FUNCTION__);
}

@end

Answer
nk.userInteractionEnabled = YES;