我正在为我的应用程序构建一个自定义滑动条。
我在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
UIView
的指定初始化方法是initWithFrame:
(如果你使用Interface Builder,还可以使用initWithCoder
),所以当你调用[self.view addSubview:[[NKHandler alloc] initWithFrame:...
时,你的初始化代码永远不会被执行。 - Guillaume