iOS 中scrollView整個頁面滑動自動居中。
在iOS中,如果整體的寬度大於單個item的寬度,自動滑動居中則不好用,解決方法如下。寬度還是設置成item的寬度。在 HFScrollViewSuperView上面addsubView。實現原理看代碼就能明白。
HFScrollViewSuperView
#import <UIKit/UIKit.h>
@interface HFScrollViewSuperView : UIView
@property (nonatomic, strong) UIScrollView *scrollView;
@end
#import "HFScrollViewSuperView.h"
@implementation HFScrollViewSuperView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if ([self pointInside:point withEvent:event]) {
for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
CGPoint convertedPoint = [subview convertPoint:point fromView:self];
UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
if ([hitTestView isKindOfClass:[UIButton class]]) {
return hitTestView;
}
}
return self.scrollView;
}
return nil;
}
@end