ios - 无法将从 XIB 创建的自定义 UIView 子类转换为我需要的类(仅限 UIView)

标签 ios swift xcode uiview xib

我所做的是:

1) 创建了一个 .xib 文件 TranslationInfoWindow.xib:

xib file for the info window

2) 创建包含以下内容的 TranslationInfoWindow.swift 文件:

import UIKit

class TranslationInfoWindow: UIView {

    // MARK: - Initializers

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    // MARK: - Private Helper Methods

    // Performs the initial setup.
    private func setupView() {
        let view = viewFromNibForClass()
        view.frame = bounds

        // Auto-layout stuff.
        view.autoresizingMask = [
            UIViewAutoresizing.flexibleWidth,
            UIViewAutoresizing.flexibleHeight
        ]

        // Show the view.
        addSubview(view)
    }

    // Loads a XIB file into a view and returns this view.
    private func viewFromNibForClass() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view
    }

    @IBOutlet weak var avatarImageView: RoundedImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var usersLabel: UILabel!
}

3)这里我尝试初始化我的自定义 View :

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    //             FIXME: There is a UIView but it doesn't want to be casted in TranslationInfoWindow
    if let infoWindow = Bundle.main.loadNibNamed(
        "TranslationInfoWindow", owner: view, options: nil)?.first as? TranslationInfoWindow {
        return infoWindow
    } else {
        return nil
    }
}

现在,如果我尝试运行该项目,则会出现以下错误: My error

我做错了什么?


更新:

这是 xib 的层次结构: enter image description here

最佳答案

在 Interface Builder 中,您是否将 Identity Inspector(左数第三个)选项卡中的类名从 UIView 更改为您的自定义类名? screen grab of IB

关于ios - 无法将从 XIB 创建的自定义 UIView 子类转换为我需要的类(仅限 UIView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332460/

相关文章:

ios - 使用未声明的类型 "SimplePing"

ios - XCTest 不链接 iOS 框架

objective-c - 如何将 .a C 静态库添加到 Xcode 并在那里使用它?

ios - 检查具有 Apple Pay 功能的设备

ios - Swift - 将 html 字符串转换为属性字符串并再次返回时,字体大小会增加

ios - 使用 Parse 替换 Core Data

iphone - 关于xcode中浮点值的问题

ios - SKEffectNode 遍历 child 崩溃(iOS10 Spritekit)

ios - 如何启用用户注册 - eJabberd for mac?

ios - 控制两个不同的collectionview