我遇到问题,当我在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;
}
ScrollView.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);
}
答案 0 :(得分:4)
在
- (id)initWithFrame:(CGRect)frame
添加
self.delegate = self;
或在AppDelegate.m中,在scrollview inited之后,添加此代码
scrollview.delegate = self;
当然,您必须实现委托方法
scrollViewDidScroll:
并且不要忘记在AppDelegate.h中添加以下代码
@interface AppDelegate : UIResponder <UIApplicationDelegate,UIScrollViewDelegate>
答案 1 :(得分:3)
对于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.
}
}
答案 2 :(得分:3)
第1步:为UIViewController类创建委托:
@interface ViewController : UIViewController <UIScrollViewDelegate>
步骤2:然后为UIScrollView
对象添加委托:
scrollview.delegate = self;
步骤3:实现委托方法如下:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Do your stuff here...
// You can also track the direction of UIScrollView here....
// to check the y position use scrollView.contentOffset.y
}
你走了。借助上述3个步骤,您可以将ScrollViewDidScroll
方法集成到我们的Objective-C
类中。