UIView 中的协议无法更改 viewController 中的对象?

Protocol in UIView cannot change object in viewController?

我想在 drawRect UIView 中放置一个横幅,但它在第 'bannerView.rootViewController = self' 行发出警告。所以我把横幅放在它的 viewController 中。我希望 drawRect 中的值改变横幅的位置。该值可以打印出来,但横幅拒绝移动。这是代码:

ViewController:

class ViewController: UIViewController, GADBannerViewDelegate,ChangeBannerDelegate 

    // var bannerView:GADBannerView!  // shows nil when run func changeBanner(), has to use the following
    var  bannerView = GADBannerView(adSize: kGADAdSizeBanner) 

    override func viewDidLoad() {
        super.viewDidLoad()

        waveView = WaveWater(frame: self.view.bounds)
        bannerView = GADBannerView(adSize: kGADAdSizeBanner)
        bannerView.frame = CGRect(x: 0, y: self.view.bounds.height-50, width: self.view.bounds.width, height: 50)
        bannerView.adUnitID = "xxxxxxxxxxxx"
        bannerView.rootViewController = self
        bannerView.delegate = self

        self.view.addSubview(bannerView)
        bannerView.loadRequest(GADRequest())

        // set other things...
    }

    func changeBanner(y:CGFloat){

        bannerView.frame.origin.y = y
        println(bannerView.frame.origin.y) // can print 'y', and banner.frame.origin.y was changed, but banner stays where it is

    }

UIView:

protocol ChangeBannerDelegate:NSObjectProtocol,GADBannerViewDelegate{

    func changeBanner(y:CGFloat)

}

class WaveWater: UIView, UIGestureRecognizerDelegate {

    var bannerDelegate:ChangeBannerDelegate?
    override init(frame: CGRect) {

        super.init(frame: frame)

        self.bannerDelegate = ViewController()
        changeBanner(50) // place it here just for a try
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawRect(rect: CGRect) {
        //drawing things........
    }
}

您正在 init(frame:) 方法中将 WaveWater 视图的 bannerDelegate 设置为 ViewController 的新实例:

self.bannerDelegate = ViewController()

它应该设置为您已经拥有的视图控制器的实例,最好的位置是在您在 viewDidLoad 中创建视图之后:

override func viewDidLoad() {
    super.viewDidLoad()

    waveView = WaveWater(frame: self.view.bounds)
    waveView.bannerDelegate = self

    ...
}