如何在 UIScrollView 中实现 scrollViewDidScroll

col*_*unn 5 objective-c uikit ios

我遇到了一个问题,当我scrollViewDidScroll在我的子类中调用方法时UIScrollView什么也没有发生。这是我的代码:

AppDelegate.m

#import "ScrollView.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    CGRect screenRect = [[self window] bounds];

    ScrollView *scrollView = [[ScrollView alloc] initWithFrame:screenRect];
    [[self window] addSubview:scrollView];
    [scrollView setContentSize:screenRect.size];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

滚动视图.m

#import "AppDelegate.h"
#import "ScrollView.h"

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        NSString *imageString = [NSString stringWithFormat:@"image"];
        UIImage *image = [UIImage imageNamed:imageString];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        [super addSubview:imageView];
    }
    return self;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"%f", scrollView.contentOffset.y);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

- (id)initWithFrame:(CGRect)frame
Run Code Online (Sandbox Code Playgroud)

添加

self.delegate = self;
Run Code Online (Sandbox Code Playgroud)

或在 AppDelegate.m 中,在滚动视图初始化后,添加此代码

scrollview.delegate = self;
Run Code Online (Sandbox Code Playgroud)

当然,你必须实现委托方法

scrollViewDidScroll:
Run Code Online (Sandbox Code Playgroud)

并且不要忘记在 AppDelegate.h 中添加以下代码

@interface AppDelegate : UIResponder <UIApplicationDelegate,UIScrollViewDelegate>
Run Code Online (Sandbox Code Playgroud)


ViJ*_*had 5

对于 iOS10,Swift 3.0 在 UIScrollView 上实现 scrollViewDidScroll

class ViewController: UIViewController, UIScrollViewDelegate{

//In viewDidLoad Set delegate method to self.

@IBOutlet var mainScrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.mainScrollView.delegate = self

}
//And finally you implement the methods you want your class to get.
func scrollViewDidScroll(_ scrollView: UIScrollView!) {
    // This will be called every time the user scrolls the scroll view with their finger
    // so each time this is called, contentOffset should be different.

    print(self.mainScrollView.contentOffset.y)

    //Additional workaround here.
}
}
Run Code Online (Sandbox Code Playgroud)