问题由来
前段时间遇到一个需求:
列表上部分是一个tableView下半部分是webview,上下滚动的时候需要能完美接上。
因为苹果官方表明了,不推荐用户嵌套使用scrollView,官方属性肯定是无法完美解决了,只能自己想办法了。
方案调研
下面会列出几种网上找到的方案,分别介绍下优缺点。
方案一:
webview
放在tableview
的cell
中,在scrollViewDidScroll:
中通过contentOffset
属性来控制具体滚动的scrollView
.
这个方案源代码就不列出来了,网上有一堆。说下优缺点。
优点:
- 上手简单,思路也比较容易理解
缺点:
-
要防止收拾冲突需要实现tableView和webView的子类,并重载下面的方法
- (BOOL*)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;
其中一个scrollView滑动到临界点,需要切换另一个scrollView滑动时,会出现减速效果对接不上的问题。
另外这种方案因为需要cell中的webview与tableView属性关联,或多或少会造成一些耦合。
方案二:
直接将webview
的frame
撑满到contentSize
大小
看到这个方案的时候,我是一愣,还能这么玩。于是就顺手尝试了下。核心实现逻辑就是KVO webview
的contentSize
,contentSize变化时reload下tableView,改变承载webview的cell的高度。
这个方案实现上是最简单的,但是debug发现webview占用的内存大大增加。原因是系统对webview做了优化,没有显示出来的部分实际不会全部渲染。但是如果将webview全部撑开了,会导致所有内容全部直接渲染。
方案三:
UIKit Dynamics模仿UIScrollView。
说实话当看到这个方案时,内心确实有一种打开新世界大门的感觉。曾今一度我都准备选择这个方案了,但是当我准备上手的时候,发现scrollView的各种效果(惯性滚动, 弹性, 橡皮筋)实现起来真的是不容易了,而且还需要调整各种参数。要达到UIScrollView原生效果效果真的是不容易,最终还是选择了放弃。感兴趣的同学可以去用UIKit Dynamics模仿UIScrollView了解。
方案四:
一个rootScrolleView
作为最底成的scrollView
,将一个contentView
(UIView
)放在rootScrolleView
上, tableview
和webview
都放在contentView
上,并禁止tableView
和webView
的滚动。当rootScrolleView
滚动时,动态调整contentView
的originY
或者tableView
和webView
的contentOffset
。
方案四的缺点是计算什么时候进行contentView 的偏移?和什么时候进行tableView的contentOffset修改?是比较复杂的过程。但这也是方案四的优点,如果算法实现的足够好,可以实现多级联动的scrollView是可以没有上限的(也就是说可以做到很多个scrollview联动,甚至包括其他的UIView也可以实现联动)。
说到这里,大家应该页猜到了方案四就是我当前使用的方案,下面我用这个方案实现的一个通用的多个scrollView多级联动的方案。
1、监听UIScrollView的contentSize和bounds的变化,实时调整rootScrollView的cotnentSize和contentView中subview的originY。
注意UIScrollView需要contentSize和bounds的变化,而UIView只需要监听bounds的变化就可以了。
2、rootScrolleView在scroll过程中,需要重新计算contentView的originY和scrollView的contentOffset来保证scrollView的相应区域显示在屏幕上。
效果如下:
下面附上实现源码
#import
@class SKContainerScrollView;
@protocol SKContainerScrollViewDelegate
- (void)containerScrollViewAlreadyAtBottom:(SKContainerScrollView *)containScrollView ;
@end
@interface SKContainerScrollView : UIScrollView
@property (nonatomic, weak) id containDelegate;
- (instancetype)initWithFrame:(CGRect)frame componentViews:(NSArray *)componentViews;
@end
#import "SKContainerScrollView.h"
#import
#import
@interface SKContainerScrollView()
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) NSArray *componentViews;
@property (nonatomic, strong) NSMutableArray *lastHeights;
@property (nonatomic, strong) NSMutableArray *boundaryValues;
@end
@implementation SKContainerScrollView
#pragma mark - LifeCycle
- (instancetype)initWithFrame:(CGRect)frame componentViews:(NSArray *)componentViews {
if (self = [super initWithFrame:frame]) {
_componentViews = componentViews;
[self initSubViews];
[self addObservers];
}
return self;
}
- (void)initSubViews {
self.delegate = self;
self.alwaysBounceVertical = YES;
self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.qmui_width, self.qmui_height * 2)];
[self addSubview:self.contentView];
self.lastHeights = [NSMutableArray array];
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[WKWebView class]] || [obj isKindOfClass:[UIWebView class]]) {
[(WKWebView *)obj scrollView].scrollEnabled = NO;
} else if ([obj isKindOfClass:[UIScrollView class]]) {
((UIScrollView *)obj).scrollEnabled = NO;
} else {
//普通View
}
[self.contentView addSubview:obj];
self.lastHeights[idx] = @(obj.frame.size.height);
}];
[self updateContainer];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self updateContainer];
}
- (void)dealloc {
[self.KVOControllerNonRetaining unobserveAll];
}
#pragma mark - Observers
- (void)addObservers{
weakify(self);
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
strongify(self);
if ([obj isKindOfClass:[WKWebView class]] || [obj isKindOfClass:[UIWebView class]]) {
[self.KVOControllerNonRetaining observe:obj keyPaths:@[@"scrollView.contentSize", @"bounds"] options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id _Nullable observer, id _Nonnull object, NSDictionary * _Nonnull change) {
doBlockMainQueue(^{
strongify(self);
if ([change[FBKVONotificationKeyPathKey] isEqualToString:@"bounds"]) {
if (!CGSizeEqualToSize([change[NSKeyValueChangeNewKey] CGRectValue].size, [change[NSKeyValueChangeOldKey] CGRectValue].size) ) {
[self updateContainer];
}
} else {
[self updateContainer];
}
});
}];
} else if ([obj isKindOfClass:[UIScrollView class]]) {
[self.KVOControllerNonRetaining observe:obj keyPaths:@[@"contentSize", @"bounds"] options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id _Nullable observer, id _Nonnull object, NSDictionary * _Nonnull change) {
doBlockMainQueue(^{
strongify(self);
if ([change[FBKVONotificationKeyPathKey] isEqualToString:@"bounds"]) {
if (!CGSizeEqualToSize([change[NSKeyValueChangeNewKey] CGRectValue].size, [change[NSKeyValueChangeOldKey] CGRectValue].size) ) {
[self updateContainerForce:YES];
}
} else {
[self updateContainer];
}
});
}];
} else {
//普通View,监控Frame变化
[self.KVOControllerNonRetaining observe:obj keyPath:@"bounds" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary * _Nonnull change) {
doBlockMainQueue(^{
strongify(self);
if ([change[FBKVONotificationKeyPathKey] isEqualToString:@"bounds"]) {
if (!CGSizeEqualToSize([change[NSKeyValueChangeNewKey] CGRectValue].size, [change[NSKeyValueChangeOldKey] CGRectValue].size) ) {
[self updateContainer];
}
}
});
}];
}
}];
}
- (void)removeObservers {
[self.KVOControllerNonRetaining unobserveAll];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"scrollView.contentSize"]) {
[self updateContainer];
} else if ([keyPath isEqualToString:@"contentSize"]) {
[self updateContainer];
} else if ([keyPath isEqualToString:@"bounds"]) {
[self updateContainer];
}
}
- (void)updateContainerForce:(BOOL)force {
__block BOOL changed = NO;
__block CGFloat totalHeight = 0;
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
CGFloat lastHeight = [self.lastHeights[idx] floatValue];
CGFloat height = [self contentSizeHeightForView:obj];
if (lastHeight != height) {
self.lastHeights[idx] = @(height);
changed = YES;
}
totalHeight += height;
}];
//如果所有View高度没有变化不需要修改
if (!changed && !force) {
return;
}
self.contentSize = CGSizeMake(self.qmui_width, totalHeight);
totalHeight = 0;
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
CGFloat height = [self contentSizeHeightForView:view];
if ([view isKindOfClass:[WKWebView class]] || [view isKindOfClass:[UIWebView class]]) {
height = (height < self.qmui_height) ? height :self.qmui_height;
view.qmui_height = height <= 0.1 ? 0.1 : height;
} else if ([view isKindOfClass:[UIScrollView class]]) {
height = (height < self.qmui_height) ? height :self.qmui_height;
view.qmui_height = height;
} else {
//普通页面不需要修改宽高,内部不会改变size
}
view.qmui_top = totalHeight;
totalHeight += height;
}];
self.contentView.qmui_height = totalHeight;
totalHeight = 0;
self.boundaryValues = [NSMutableArray array];
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
CGFloat contentHeight = [self contentSizeHeightForView:view];
CGFloat boundsHeight = view.qmui_height;
CGFloat value = totalHeight + contentHeight - boundsHeight;
[self.boundaryValues addObject:@(value)];
[self.boundaryValues addObject:@(totalHeight + contentHeight)];
totalHeight += contentHeight;
}];
//Fix:contentSize变化时需要更新各个控件的位置
[self scrollViewDidScroll:self];
}
- (void)updateContainer {
[self updateContainerForce:NO];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (self != scrollView) {
return;
}
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY <= 0) {
self.contentView.qmui_top = 0;
[self.componentViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self setView:obj contentOffsetY:0];
}];
return;
}
__block NSInteger handleViewIndex = 0;
[self.boundaryValues enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (offsetY < obj.floatValue) {
handleViewIndex = idx/2;
UIView *handleView = self.componentViews[handleViewIndex];
if (idx % 2 == 0) {
//contentview不跟随scrollView滚动, componentView滚动
CGFloat preContentHeight = 0;
if (idx > 0) {
preContentHeight = [self.boundaryValues[idx - 1] floatValue];
}
self.contentView.qmui_top = offsetY - ((handleViewIndex > 0) ? self.componentViews[handleViewIndex - 1].qmui_bottom : 0);
[self setView:handleView contentOffsetY:offsetY - preContentHeight];
} else {
//contentView跟随scrollView滚动,componentView不滚动
CGFloat preContentHeight = 0;
if (idx > 1) {
preContentHeight = [self.boundaryValues[idx - 2] floatValue];
}
self.contentView.qmui_top = preContentHeight - handleView.qmui_top + [self contentSizeHeightForView:handleView] - handleView.qmui_height;
[self setView:handleView contentOffsetY:[self contentSizeHeightForView:handleView] - handleView.qmui_height];
}
*stop = YES;
} else {
UIView *view = self.componentViews[idx/2];
[self setView:view contentOffsetY:[self contentSizeHeightForView:view] - view.qmui_height];
}
}];
for (NSInteger i = handleViewIndex + 1; i < self.componentViews.count; i++) {
UIView *view = self.componentViews[i];
[self setView:view contentOffsetY:0];
}
if ([self qmui_alreadyAtBottom]) {
if ([self.containDelegate respondsToSelector:@selector(containerScrollViewAlreadyAtBottom:)]) {
[self.containDelegate containerScrollViewAlreadyAtBottom:self];
}
}
}
#pragma mark - Setter
- (void)setView:(UIView *)view contentOffsetY:(CGFloat)offsetY {
if ([view isKindOfClass:[WKWebView class]] || [view isKindOfClass:[UIWebView class]]) {
[((WKWebView *)view) scrollView].contentOffset = CGPointMake(0, offsetY);
} else if ([view isKindOfClass:[UIScrollView class]]) {
((UIScrollView *)view).contentOffset = CGPointMake(0, offsetY);
} else {
//普通View,监控Frame变化
}
}
#pragma mark - Getter
- (CGFloat)contentSizeHeightForView:(UIView *)view {
if ([view isKindOfClass:[WKWebView class]] || [view isKindOfClass:[UIWebView class]]) {
return [((WKWebView *)view) scrollView].contentSize.height;
} else if ([view isKindOfClass:[UIScrollView class]]) {
return ((UIScrollView *)view).contentSize.height;
} else {
//普通View,监控Frame变化
return view.bounds.size.height;
}
}
@end