0

我有以下符合 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”类型的值分配给“LocationInformationnCalloutView?”

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

4

3 回答 3

1

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

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

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

func loadLocationInformationCalloutView() -> LocationInformationCalloutView {
    return LocationInformationCalloutView(frame: CGRect(x: 0, y: 0, width: 240, height: 280))
}
于 2018-09-20T10:57:00.620 回答
1

你反其道而行之。您可以将子类的变量分配给超类的变量,但由于显而易见的原因,您不能做相反的事情。

首先,如果应该这样做,您的方法应该返回一个有效LocationInformationCalloutView的。如果必须,出于某种原因将其作为UIView. 然后你必须LocationInformationCalloutView在保存之前将其转换为customCalloutView.

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

注意:如果UIView传递的实际上不是LocationInformationCalloutView. 该方法最好看起来像@DávidPásztor答案显示的方式。

于 2018-09-20T10:57:06.857 回答
0

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

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

}

于 2018-09-20T10:58:20.930 回答