gpt4 book ai didi

ios - UIView 中的协议(protocol)无法更改 viewController 中的对象?

转载 作者:行者123 更新时间:2023-11-29 01:39:58 24 4
gpt4 key购买 nike

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

View Controller :

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

}

界面 View :

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........
}
}

最佳答案

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

self.bannerDelegate = ViewController()

它应该设置为您已经拥有的 View Controller 的实例,最好的位置是在您在 viewDidLoad 中创建 View 之后:

override func viewDidLoad() {
super.viewDidLoad()

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

...
}

关于ios - UIView 中的协议(protocol)无法更改 viewController 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32516549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com