我通过使用类别来做视差效果:
add and UIView into the uitableView (via category
add addObserver:forKeyPath so that whenever tableview is moving, i will reframe the view above
详情如下 UIScrollView+Parallax.h
#import <UIKit/UIKit.h>
@class ParallaxView;
@interface UIScrollView (Parallax)
@property (strong, nonatomic) ParallaxView *parallaxView;
- (void) addParallaxViewWith:(UIView*)parallaxView;
- (void) removeKVO;
@end
@interface ParallaxView : UIView
@end
UIScrollView+视差.m
static char parallaxKey;
@implementation UIScrollView (Parallax)
@dynamic parallaxView;
#pragma mark - Add parallax view to scrollView
- (void) addParallaxViewWith:(ParallaxView*)pView {
if ( !self.parallaxView) {
[self addSubview:pView];
[self setParallaxView:pView];
}
}
#pragma mark - Set parallaxView + register parallaxView as an observer
- (void) setParallaxView:(ParallaxView *)parallaxView {
objc_setAssociatedObject(self, ¶llaxKey, parallaxView, OBJC_ASSOCIATION_ASSIGN);
/* THESE LINE ARE CRASHING THE APP */
// [self addObserver:self.parallaxView
// forKeyPath:@"contentOffset"
// options:NSKeyValueObservingOptionNew
// context:nil];
}
#pragma mark - Get parallaxView
- (ParallaxView*) parallaxView {
return (objc_getAssociatedObject(self, ¶llaxKey));
}
#pragma mark - Remove
- (void)removeKVO {
[self removeObserver:self.parallaxView forKeyPath:@"contentOffset"];
}
@end
@implementation ParallaxView
-(id)init
{
//load xib from main bundle and assign it to self
self = [[[NSBundle mainBundle]loadNibNamed:@"Parallex"
owner:self
options:nil] objectAtIndex:0];
return self;
}
-(id)initWithFrame:(CGRect)frame
{
self = [self init];
[self setFrame:frame];
return self;
}
................
@end
我正在通过执行向表格添加视差
ParallaxView *pView = [[ParallaxView alloc]initWithFrame:CGRectMake(0, 0, 320, 160)];
[self.tableView addParallaxViewWith:pView];
但是,[self addObserver:forKeyPath:options:context:nil]
在没有任何线索的情况下不断使应用程序崩溃。如果我将此行注释掉并且应用程序没有崩溃但平行效果不起作用。
对此问题的任何想法。请帮忙。谢谢