scrollViewにすべてのビューを追加するには、パフォーマンスのために良いではありません。このようなビューを管理するための最良のソリューションは、UICollectionViewCell
のカスタムでUICollectionView
を使用することです。コレクションビューは、必要なものすべてを行います。ビューを再利用し、可視のrectにしたがって正しく配置します。ケースでは、UICollectionView
はそのような何かしようとし使用することはできません。
@interface SampleClass : UIViewController <UIScrollViewDelegate>
@property (nonatomic) UIScrollView *scrollView;
@property (nonatomic) NSUInteger viewsCount;
@property (nonatomic) NSDictionary<NSNumber *, UIView *> *visibleViewsByIndexes;
@end
@implementation SampleClass
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self updateViews];
[self hideInactiveViews];
}
- (void)updateViews
{
CGPoint offset = self.scrollView.contentOffset;
CGRect frame = self.scrollView.bounds;
CGRect visibleRect = frame;
visibleRect.origin.x += offset.x;
// Determine indexes of views which should be displayed.
NSMutableArray<NSNumber *> *viewsToDisplay = [NSMutableArray new];;
for (NSUInteger index = 0; index < self.viewsCount; index++) {
CGRect viewFrame = [self frameForViewAtIndex:index];
if (CGRectIntersectsRect(viewFrame, visibleRect)) {
[viewsToDisplay addObject:@(index)];
}
}
// Remove not visible views.
NSDictionary<NSNumber *, UIView *> *oldVisibleViewsByIndexes = self.visibleViewsByIndexes;
NSMutableDictionary<NSNumber *, UIView *> *newVisibleViewsByIndexes = [NSMutableDictionary new];
for (NSNumber *indexNumber in oldVisibleViewsByIndexes.allKeys) {
if (![viewsToDisplay containsObject:indexNumber]) {
UIView *viewToRemove = oldVisibleViewsByIndexes[indexNumber];
[viewToRemove removeFromSuperview];
} else {
newVisibleViewsByIndexes[indexNumber] = oldVisibleViewsByIndexes[indexNumber];
}
}
// Add new views.
for (NSNumber *indexNumber in viewsToDisplay) {
if (![oldVisibleViewsByIndexes.allKeys containsObject:indexNumber]) {
UIView *viewToAdd = [self viewAtIndex:indexNumber.unsignedIntegerValue];
viewToAdd.frame = [self frameForViewAtIndex:indexNumber.unsignedIntegerValue];
[self.scrollView addSubview:viewToAdd];
}
}
self.visibleViewsByIndexes = newVisibleViewsByIndexes;
}
- (CGRect)frameForViewAtIndex:(NSUInteger)index
{
// Return correct frame for view at index.
return CGRectZero;
}
- (UIView *)viewAtIndex:(NSUInteger)index
{
return [UIView new];
}
- (void)hideInactiveViews
{
CGPoint offset = self.scrollView.contentOffset;
CGRect frame = self.scrollView.bounds;
CGRect visibleRect = frame;
visibleRect.origin.x += offset.x;
for (UIView *view in self.visibleViewsByIndexes.allValues) {
if (CGRectContainsRect(visibleRect, view.frame)) {
// Active view.
view.alpha = 1;
} else {
// Inactive view.
view.alpha = 0.2;
}
}
}
@end
をあなたは、横軸に制限UICollectionViewを、使用して考え、そしてカスタムUICollectionViewCellsにページを作ることがありますか?それはあなたのためにすべての重労働を行うだろう。 – Stephen
大きなポイントスティーブン。残念ながら、既存の多くの機能がUIScrollViewテンプレートで作成されており、collectionViewに調整することはできません。 – daspianist
あなたはいつそれらを消滅させますか?スクロールが終了し、スクロールが開始されると表示されます。非アクティブなページはスクロールするとアクティブになるので(何とか表示されるはずです)、どのように見たいのですか? – timaktimak