【问题标题】:Detect scrolling in Subclass of UIScrollView在 UIScrollView 的子类中检测滚动
【发布时间】:2011-04-15 08:06:35
【问题描述】:

早上好,

我创建了 UIScrollView 的子类,现在我想知道用户何时在我的子类中滚动。为此,我将其实现如下:

ImageScroller.h

@interface UIImageScroller : UIScrollView <UIScrollViewDelegate> {

ImageScroller.m(在@implementation 中)

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSLog(@"did scroll");
}

问题是,scrollViewDidScroll 方法似乎没有被触发。 有没有可能让它工作?

我也尝试将委托设置为自己,但它不起作用。

 - (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        self.directionalLockEnabled = YES;
        [self setDelegate:self];
    }
    return self;
}

我在我的 XIB 文件中添加了一个 ScrollView,并将 Class 设置为我的 ImageScroller。我还设置了 Fileowner 并在 ViewController 的 .h 文件中使用 UIScrollViewDelegate 以及在 .m 文件中实现方法 scrollViewDidScroll。

当我在 XIB 的 .m 文件的代码中设置 ImageScroller 的委托时,例如 [imageScroller setDelegate:imageScroller] scrollViewDidScroll 在我的 ImageScroller-Subclass 中被触发,但我的 ViewController 中的那个没有被触发,但我需要两者。

有什么解决办法吗?

提前感谢您的回答。

【问题讨论】:

    标签: iphone uiscrollview subclass


    【解决方案1】:

    我在创建 UIScrollView 的子类时遇到了同样的问题,但通过这种方式解决了。如上所述,您可以将自己(子类实例)设置为委托,但这就是我所做的。

    在子类中我覆盖了以下方法

    //Override this to detect when the user is scrolling, this is also triggered during view
    //layout.  Here you can check your deceleration rate and determine when the scrolling has
    //grinded to a halt.
    -(void)setContentOffset:(CGPoint)contentOffset
    
    //Override this to detect when the view has been resized (just a handy override)
    -(void)setFrame:(CGRect)frame;
    

    就其他 UIScrollViewDelegate 方法而言,我认为应该由 View Controller 负责处理。

    【讨论】:

      【解决方案2】:

      我认为你可以尝试设置 self.delegate = self;接收事件。

      【讨论】:

      • 我试过这样,但由于某种原因它不起作用。 - (id)initWithCoder:(NSCoder *)aDecoder { if ((self = [super initWithCoder:aDecoder])) { self.directionalLockEnabled = YES; [自我设置委托:自我]; } 返回自我; }
      • 我在我的 XIB 文件中添加了一个 ScrollView,并将 Class 设置为我的 ImageScroller。我还设置了 Fileowner 并在 ViewController 的 .h 文件中使用 UIScrollViewDelegate 以及在 .m 文件中实现方法 scrollViewDidScroll。这可能是个问题吗?
      • 我第一次没有得到它 :) 所以你的委托方法有效,但只在你的委托(滚动视图)中工作?事情本来就是这样,因为只有一个代表。我认为您可以将代理设置为您的控制器,并使其像这样- (void)scrollViewDidScroll:(UIScrollView *)scrollView { //do controller stuff here [self.view scrollViewDidScroll:(UIScrollView *)self.view]; } 但我仍然不确定这是否是问题所在。
      【解决方案3】:

      如果有人正在寻找 Swift 的答案,就这么简单:

      override var contentOffset: CGPoint {
          didSet {
              if contentOffset != oldValue {
                  //same as scrollViewDidScroll
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        • 2012-09-25
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多