我有一个滚动视图,它是屏幕的宽度,但只有大约70像素高。它包含许多我希望用户可以选择的50 x 50图标(周围带有空格)。但是我始终希望滚动视图以分页的方式运行,始终以图标居中停止。
如果图标是屏幕的宽度,那将不是问题,因为UIScrollView的分页会处理它。但是因为我的小图标远远小于内容大小,所以它不起作用。
我之前在应用程序AllRecipes中已经看到了这种行为。我只是不知道该怎么做。
如何按图标大小进行分页工作?
Answers:
尝试使滚动视图小于屏幕尺寸(沿宽度方向),但取消选中IB中的“剪辑子视图”复选框。然后,在其上覆盖一个透明的userInteractionEnabled = NO视图(全角),该视图将覆盖hitTest:withEvent:以返回您的滚动视图。那应该给你你想要的东西。有关更多详细信息,请参见此答案。
还有另一种解决方案,可能比将滚动视图与另一个视图叠加并覆盖hitTest好一点。
您可以继承UIScrollView并重写其pointInside。然后,滚动视图可以响应其框架外的触摸。当然其余都是一样的。
@interface PagingScrollView : UIScrollView {
UIEdgeInsets responseInsets;
}
@property (nonatomic, assign) UIEdgeInsets responseInsets;
@end
@implementation PagingScrollView
@synthesize responseInsets;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGPoint parentLocation = [self convertPoint:point toView:[self superview]];
CGRect responseRect = self.frame;
responseRect.origin.x -= responseInsets.left;
responseRect.origin.y -= responseInsets.top;
responseRect.size.width += (responseInsets.left + responseInsets.right);
responseRect.size.height += (responseInsets.top + responseInsets.bottom);
return CGRectContainsPoint(responseRect, parentLocation);
}
@end
return [self.superview pointInside:[self convertPoint:point toView:self.superview] withEvent:event];
@amrox @Split如果您具有充当裁剪视图的超级视图,则不需要responseInsets。
可接受的答案非常好,但是仅适用于UIScrollView
该类,而不能用于其后代。例如,如果您有很多视图并转换为UICollectionView
,则将无法使用此方法,因为集合视图将删除它认为“不可见”的视图(因此即使它们未被裁剪,它们也消失)。
关于那条评论 scrollViewWillEndDragging:withVelocity:targetContentOffset:
我认为,是正确的答案。
您可以做的是,在此委托方法中,您可以计算当前页面/索引。然后确定速度和目标偏移量是否值得“下一页”移动。您可以非常接近pagingEnabled
行为。
注意:这些天我通常是RubyMotion开发人员,因此请为正确性证明此Obj-C代码。很抱歉,将camelCase和snake_case混合使用,我复制并粘贴了大部分代码。
- (void) scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetOffset
{
CGFloat x = targetOffset->x;
int index = [self convertXToIndex: x];
CGFloat w = 300f; // this is your custom page width
CGFloat current_x = w * [self convertXToIndex: scrollView.contentOffset.x];
// even if the velocity is low, if the offset is more than 50% past the halfway
// point, proceed to the next item.
if ( velocity.x < -0.5 || (current_x - x) > w / 2 ) {
index -= 1
}
else if ( velocity.x > 0.5 || (x - current_x) > w / 2 ) {
index += 1;
}
if ( index >= 0 || index < self.items.length ) {
CGFloat new_x = [self convertIndexToX: index];
targetOffset->x = new_x;
}
}
convertXToIndex:
和convertIndexToX:
?
velocity
0举起手时,它会弹回,这很奇怪。所以我有一个更好的答案。
- (void) scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetOffset
{
static CGFloat previousIndex;
CGFloat x = targetOffset->x + kPageOffset;
int index = (x + kPageWidth/2)/kPageWidth;
if(index<previousIndex - 1){
index = previousIndex - 1;
}else if(index > previousIndex + 1){
index = previousIndex + 1;
}
CGFloat newTarget = index * kPageWidth;
targetOffset->x = newTarget - kPageOffset;
previousIndex = index;
}
kPageWidth是您希望页面的宽度。kPageOffset是如果您不希望单元格保持左对齐(即,如果希望它们居中对齐,请将其设置为单元格宽度的一半)。否则,它应该为零。
这也将仅允许一次滚动一页。
看看上的-scrollView:didEndDragging:willDecelerate:
方法UIScrollViewDelegate
。就像是:
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
int x = scrollView.contentOffset.x;
int xOff = x % 50;
if(xOff < 25)
x -= xOff;
else
x += 50 - xOff;
int halfW = scrollView.contentSize.width / 2; // the width of the whole content view, not just the scroll view
if(x > halfW)
x = halfW;
[scrollView setContentOffset:CGPointMake(x,scrollView.contentOffset.y)];
}
这不是完美的-最后,我尝试了这段代码,从橡皮筋卷轴返回时出现了一些丑陋的行为(我记得是跳跃的)。您只需将滚动视图的bounces
属性设置为,就可以避免这种情况NO
。
由于似乎尚未允许我发表评论,因此我将在此处将我的评论添加到诺亚的答案中。
我已经通过Noah Witherspoon描述的方法成功实现了这一目标。我通过仅setContentOffset:
在scrollview超出其边缘时不调用该方法来解决跳转行为。
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// Don't snap when at the edges because that will override the bounce mechanic
if (self.contentOffset.x < 0 || self.contentOffset.x + self.bounds.size.width > self.contentSize.width)
return;
...
}
我还发现我需要实现该-scrollViewWillBeginDecelerating:
方法UIScrollViewDelegate
以捕获所有情况。
我尝试了上面的解决方案,该解决方案使用pointInside:withEvent:覆盖了透明视图。这对我来说效果很好,但在某些情况下无法解决-请参阅我的评论。我最终只是自己实现了分页,并结合使用scrollViewDidScroll来跟踪当前页面索引,并使用scrollViewWillEndDragging:withVelocity:targetContentOffset和scrollViewDidEndDragging:willDecelerate捕捉到适当的页面。请注意,will-end方法仅在iOS5 +上可用,但是如果速度!= 0,则可以很好地用于定位特定的偏移量。特别是,您可以告诉调用方您希望滚动视图随动画一起降落在何处。特定方向。
创建滚动视图时,请确保设置以下内容:
scrollView.showsHorizontalScrollIndicator = false;
scrollView.showsVerticalScrollIndicator = false;
scrollView.pagingEnabled = true;
然后将子视图以等于其索引*滚动条高度的偏移量添加到滚动条中。这是用于垂直滚动条的:
UIView * sub = [UIView new];
sub.frame = CGRectMake(0, index * h, w, subViewHeight);
[scrollView addSubview:sub];
如果现在运行它,视图将被隔开,并且启用了分页功能,它们可以一次滚动一个。
因此,将其放入您的viewDidScroll方法中:
//set vars
int index = scrollView.contentOffset.y / h; //current index
float y = scrollView.contentOffset.y; //actual offset
float p = (y / h)-index; //percentage of page scroll complete (0.0-1.0)
int subViewHeight = h-240; //height of the view
int spacing = 30; //preferred spacing between views (if any)
NSArray * array = scrollView.subviews;
//cycle through array
for (UIView * sub in array){
//subview index in array
int subIndex = (int)[array indexOfObject:sub];
//moves the subs up to the top (on top of each other)
float transform = (-h * subIndex);
//moves them back down with spacing
transform += (subViewHeight + spacing) * subIndex;
//adjusts the offset during scroll
transform += (h - subViewHeight - spacing) * p;
//adjusts the offset for the index
transform += index * (h - subViewHeight - spacing);
//apply transform
sub.transform = CGAffineTransformMakeTranslation(0, transform);
}
子视图的框架仍然间隔开,我们只是在用户滚动时通过变换将它们一起移动。
此外,您还可以访问上面的变量p,该变量可以用于其他操作,例如子视图中的alpha或转换。当p == 1时,该页面已完全显示,或者趋向于1。
尝试使用scrollView的contentInset属性:
scrollView.pagingEnabled = YES;
[scrollView setContentSize:CGSizeMake(height, pageWidth * 3)];
double leftContentOffset = pageWidth - kSomeOffset;
scrollView.contentInset = UIEdgeInsetsMake(0, leftContentOffset, 0, 0);
可能需要花一些时间才能获得所需的分页。
与发布的替代方法相比,我发现此方法更干净。使用scrollViewWillEndDragging:
委托方法的问题是缓慢甩动的加速度是不自然的。
这是唯一解决该问题的方法。
import UIKit
class TestScrollViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var cellSize:CGFloat!
var inset:CGFloat!
var preX:CGFloat=0
let pages = 8
override func viewDidLoad() {
super.viewDidLoad()
cellSize = (self.view.bounds.width-180)
inset=(self.view.bounds.width-cellSize)/2
scrollView=UIScrollView(frame: self.view.bounds)
self.view.addSubview(scrollView)
for i in 0..<pages {
let v = UIView(frame: self.view.bounds)
v.backgroundColor=UIColor(red: CGFloat(CGFloat(i)/CGFloat(pages)), green: CGFloat(1 - CGFloat(i)/CGFloat(pages)), blue: CGFloat(CGFloat(i)/CGFloat(pages)), alpha: 1)
v.frame.origin.x=CGFloat(i)*cellSize
v.frame.size.width=cellSize
scrollView.addSubview(v)
}
scrollView.contentSize.width=cellSize*CGFloat(pages)
scrollView.isPagingEnabled=false
scrollView.delegate=self
scrollView.contentInset.left=inset
scrollView.contentOffset.x = -inset
scrollView.contentInset.right=inset
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
preX = scrollView.contentOffset.x
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let originalIndex = Int((preX+cellSize/2)/cellSize)
let targetX = targetContentOffset.pointee.x
var targetIndex = Int((targetX+cellSize/2)/cellSize)
if targetIndex > originalIndex + 1 {
targetIndex=originalIndex+1
}
if targetIndex < originalIndex - 1 {
targetIndex=originalIndex - 1
}
if velocity.x == 0 {
let currentIndex = Int((scrollView.contentOffset.x+self.view.bounds.width/2)/cellSize)
let tx=CGFloat(currentIndex)*cellSize-(self.view.bounds.width-cellSize)/2
scrollView.setContentOffset(CGPoint(x:tx,y:0), animated: true)
return
}
let tx=CGFloat(targetIndex)*cellSize-(self.view.bounds.width-cellSize)/2
targetContentOffset.pointee.x=scrollView.contentOffset.x
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: velocity.x, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.allowUserInteraction], animations: {
scrollView.contentOffset=CGPoint(x:tx,y:0)
}) { (b:Bool) in
}
}
}
这是我的答案。在我的示例中,collectionView
具有节标题的a是我们要使其具有自定义isPagingEnabled
效果的scrollView ,而单元格的高度是一个恒定值。
var isScrollingDown = false // in my example, scrollDirection is vertical
var lastScrollOffset = CGPoint.zero
func scrollViewDidScroll(_ sv: UIScrollView) {
isScrollingDown = sv.contentOffset.y > lastScrollOffset.y
lastScrollOffset = sv.contentOffset
}
// 实现 isPagingEnabled 效果
func scrollViewWillEndDragging(_ sv: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let realHeaderHeight = headerHeight + collectionViewLayout.sectionInset.top
guard realHeaderHeight < targetContentOffset.pointee.y else {
// make sure that user can scroll to make header visible.
return // 否则无法手动滚到顶部
}
let realFooterHeight: CGFloat = 0
let realCellHeight = cellHeight + collectionViewLayout.minimumLineSpacing
guard targetContentOffset.pointee.y < sv.contentSize.height - realFooterHeight else {
// make sure that user can scroll to make footer visible
return // 若有footer,不在此处 return 会导致无法手动滚动到底部
}
let indexOfCell = (targetContentOffset.pointee.y - realHeaderHeight) / realCellHeight
// velocity.y can be 0 when lifting your hand slowly
let roundedIndex = isScrollingDown ? ceil(indexOfCell) : floor(indexOfCell) // 如果松手时滚动速度为 0,则 velocity.y == 0,且 sv.contentOffset == targetContentOffset.pointee
let y = realHeaderHeight + realCellHeight * roundedIndex - collectionViewLayout.minimumLineSpacing
targetContentOffset.pointee.y = y
}
精致的Swift版本的UICollectionView
解决方案:
override func viewDidLoad() {
super.viewDidLoad()
collectionView.decelerationRate = .fast
}
private var dragStartPage: CGPoint = .zero
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
dragStartOffset = scrollView.contentOffset
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// Snap target offset to current or adjacent page
let currentIndex = pageIndexForContentOffset(dragStartOffset)
var targetIndex = pageIndexForContentOffset(targetContentOffset.pointee)
if targetIndex != currentIndex {
targetIndex = currentIndex + (targetIndex - currentIndex).signum()
} else if abs(velocity.x) > 0.25 {
targetIndex = currentIndex + (velocity.x > 0 ? 1 : 0)
}
// Constrain to valid indices
if targetIndex < 0 { targetIndex = 0 }
if targetIndex >= items.count { targetIndex = max(items.count-1, 0) }
// Set new target offset
targetContentOffset.pointee.x = contentOffsetForCardIndex(targetIndex)
}
旧线程,但值得一提的是我对此的看法:
import Foundation
import UIKit
class PaginatedCardScrollView: UIScrollView {
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
_setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_setup()
}
private func _setup() {
isPagingEnabled = true
isScrollEnabled = true
clipsToBounds = false
showsHorizontalScrollIndicator = false
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Asume the scrollview extends uses the entire width of the screen
return point.y >= frame.origin.y && point.y <= frame.origin.y + frame.size.height
}
}
这样,您可以a)使用scrollview的整个宽度进行平移/滑动操作,b)能够与scrollview原始范围之外的元素进行交互
对于UICollectionView问题(对我来说,这是一个水平滚动卡集合的UITableViewCell,带有即将到来的/先前卡的“ ticker”),我只需要放弃使用Apple的本机分页。Damien的github解决方案对我来说很棒。您可以通过增加标题宽度并在第一个索引处将其动态调整为零来调整股票行情指示器的大小,因此最终不会留有较大的空白边距