我正在为我的应用程序构建一个自定义滑块。
我在 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)]];
这就是课程。我究竟做错了什么??
这.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