iOS UIScrollView滚动检测

iOS UIScrollView scrolling detection

我正在开发一种带有定制的 UITextView 副本。现在我需要实现选择光标(请参阅下面原始 UITextView 的屏幕截图)

正如我从 Debug View Hierarchy 中发现的那样,Apple 开发人员将这些点绘制在单独的 Window 上以避免剪裁,并且当 UIScrollView 开始拖动时,他们将这些点移动到 UITextView 内,当它停止拖动时,他们将其移回单独的 window。这种方法的唯一问题是我如何检测我的某些 TextView superview 何时 UIScrollView 而它们 start/end 滚动?为每个 UIScrollView-type superviews 设置委托看起来很糟糕并且会带来很多麻烦,因为如果需要我将需要管理多个委托(甚至检测那里的变化)。有什么想法吗?

您可以对所有 UIScrollView 使用相同的滚动视图委托。

scrollView1.delegate = self
scrollView2.delegate = self
etc...

只需实现委托方法,并根据需要对每个滚动视图采取不同的操作。通过引用 class 中的属性或设置标记来执行此操作。

func scrollViewDidScroll(scrollView: UIScrollView!) {
   if scrollView.tag == 0 {
     // Do stuff
   } else {
     // Do other stuff
   }
}
/*
 In your viewDidLoad or where ever you create the UITextView call this :[self checkParentViewOfTextView:textField];
*/

-(void)checkParentViewOfTextView:(UITextView*)txv {
    if ([txv.superview isKindOfClass:[UIScrollView class]]) { // Check if the superview if UIScrollView
        UIScrollView *superScroll =(UIScrollView*) txv.superview;
        superScroll.delegate = self;// In order to call the delegate methods below
        superScroll.tag = 5; // Set a tag to access the current scrollView at these delegate methods
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //Any scrollView did begin scrolling
    if (scrollView.tag == 5) {
        //Actions for your scrollView
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //Any scrollView did end scrolling
    if (scrollView.tag == 5) {
        //Actions for your scrollView
    }
}