UIScrollViewDelegate未在自定义类中调用

时间:2016-11-15 03:31:36

标签: ios swift uiscrollviewdelegate

当我实例化并向我的self.view类中的ViewController添加滚动视图并将滚动视图的委托设置为self时,将调用委托函数。如下所示:

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var smallView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let width = Double(view.frame.width)
        let height = Double(view.frame.height)
        let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
        let scrollView = UIScrollView(frame: frame)
        //scrollView.backgroundColor = UIColor.blue
        let size = CGSize(width: width + 300, height:1000)
        scrollView.contentSize = size
        smallView.addSubview(scrollView)
        scrollView.delegate = self

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("Gets called.")
    }

}

但是,当我创建一个自定义类(在本例中称为PhotoBooth)并调用try来调用此自定义类中的委托函数时,不会调用这些函数。这是我的自定义类:

import Foundation
import UIKit

class PhotoBooth: NSObject, UIScrollViewDelegate {

    private var boothView: UIView
    //private var scrollView: UIScrollView

    init(view: UIView) {

        boothView = view

    }

    func startSession() {
        let width = Double(boothView.frame.width)
        let height = Double(boothView.frame.height)
        let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
        let scrollView = UIScrollView(frame: frame)
        //scrollView.backgroundColor = UIColor.blue
        let size = CGSize(width: width + 300, height:1000)
        scrollView.contentSize = size
        boothView.addSubview(scrollView)
        scrollView.delegate = self
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("paisdjfij")
    }

}

我在我的ViewController中实例化了这样的课程:

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var smallView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let photoBooth = PhotoBooth(view: self.view)
        photoBooth.startSession()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

问题的任何解决方案?请让我知道,并提前感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

而不是尝试这个你应该使用协议来调用自定义类中的滚动视图。它看起来会像这样。

<强> CustomClass.h

@protocol CustomDelegate <NSObject>

-(void)customDelegateMethod;

@end

@interface CustomClass : UIScrollView <UIScrollViewDelegate>
{
    id<CustomDelegate> delegate
}

<强> CustomClass.m

-(void) methodScrollView
{
    [self.delegate customDelegateMethod];
}

<强> ViewController.h

@interface ViewController: UIViewController <CustomDelegate>
{
}

<强> ViewController.m

-(void)makeCustomScrollView
{
     CustomClass *objCustom = [[CustomClass alloc] init];
     objCustom.delegate = self;
     //other stuff
}
-(void)customDelegateMethod
{
}