我正在为我的应用程序构建自定义滑块。
我在Github上找到了一个图书馆作为灵感。
我创建了文件NKSlider
作为UIView
的子类,并像库一样在其上实现了drawRect
并实现了方法:touchesMoved:withEvent:
和touchesBegan:withEvent:
。但是没有任何触摸事件被调用。
这是我如何将此自定义视图添加到我的视图控制器中:
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)]];
这是 class 。我究竟做错了什么??
.h
#import <UIKit/UIKit.h>
@interface NKHandler : UIView
@end
和
.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
最佳答案
nk.userInteractionEnabled = YES;