Canot 将类型"UIView"的值分配给符合 UIView 的类型 --类--



我有以下符合UIView的类:

import UIKit
class LocationInformationCalloutView: UIView {
:
:

然后我有第二节课,看起来像这样:

class LocationInformationAnnotationView: MKAnnotationView {
weak var customCalloutView : LocationInformationCalloutView?
}
}
:
:

所以你可以看到我有一个名为customAnnotationView的变量,它的类型为LocationInformationCalloutView

类型为UIView

loadLocationInformationCalloutView()函数如下所示(只是一个返回 UIView 的函数(:

func loadLocationInformationCalloutView() -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 280))
return view
}

但是,在调用此行代码时:

self.customCalloutView = newCustomCalloutView

在此代码块中:

override func setSelected(_ selected: Bool, animated: Bool) {
if selected {
self.customCalloutView?.removeFromSuperview()
if let newCustomCalloutView = loadLocationInformationCalloutView() {
newCustomCalloutView.frame.origin.x -= newCustomCalloutView.frame.width / 2.0 - (self.frame.width / 2.0)
newCustomCalloutView.frame.origin.y -= newCustomCalloutView.frame.height
self.addSubview(newCustomCalloutView)
self.customCalloutView = newCustomCalloutView
if animated {
self.customCalloutView!.alpha = 0.0
UIView.animate(withDuration: 1.8, animations: {
self.customCalloutView!.alpha = 1.0
})

我收到以下错误:

无法将类型"UIView"的值分配给类型"位置信息n标注视图?"

有人可以对此有所了解并帮助我解决这个问题吗?任何帮助 si 非常感谢,谢谢!

LocationInformationCalloutView继承自UIView,这意味着您可以将LocationInformationCalloutView的实例分配给类型为UIView的属性,但不能反过来这样做。

在第self.customCalloutView = newCustomCalloutView行,您正在尝试将UIView实例分配给类型LocationInformationCalloutView的属性,该属性不起作用,因为不能使用父类代替子实例。

您需要将loadLocationInformationCalloutView()的返回类型更改为LocationInformationCalloutView而不是UIView

func loadLocationInformationCalloutView() -> LocationInformationCalloutView {
return LocationInformationCalloutView(frame: CGRect(x: 0, y: 0, width: 240, height: 280))
}

你反过来得到了它。您可以将子类的变量分配给超类的变量,但由于显而易见的原因,您不能做相反的事情。

首先,如果应该返回有效的LocationInformationCalloutView,您的方法应该返回。如果必须,出于某种原因将其作为UIView返回。然后,您必须将其转换为LocationInformationCalloutView,然后再将其保存在customCalloutView中。

if let validCustomCalloutView = newCustomCalloutView as? LocationInformationCalloutView {
self.customCalloutView = validCustomCalloutView
}

注意:如果传递的UIView实际上不是LocationInformationCalloutView的实例,则转换将失败。该方法最好看起来像答案显示@DávidPásztor。

您是否尝试使用自己的类类型实例化标注视图,如下所示:

func loadLocationInformationCalloutView() -> LocationInformationCalloutView? {
let view = LocationInformationCalloutView(frame: CGRect(x: 0, y: 0, width: 240, height: 280))
return view

}

最新更新