【问题标题】:Cannot cast my custom UIView subclass created from XIB to the class I need (only UIView)无法将我从 XIB 创建的自定义 UIView 子类转换为我需要的类(仅限 UIView)
【发布时间】:2017-11-04 01:45:54
【问题描述】:

我所做的是:

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

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) 在这里我尝试初始化我的自定义视图:

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

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

我做错了什么?


更新:

这是 xib 的层次结构:

【问题讨论】:

  • 请张贴一张你的xib树的截图。还要检查问题实际上是演员表
  • 如果您有控制台,请在控制台中显示错误消息。否则,记录let view = nib.instantiate(withOwner:self, options:nil).first的(类)
  • @FernandoMazzon 添加了xib的层次结构
  • class func instanceFromNib() -> UIView { return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView } 看到这个。
  • 你能登录Bundle.main.loadNibNamed( "TranslationInfoWindow", owner: view, options: nil)吗?

标签: ios swift xcode uiview xib


【解决方案1】:

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

【讨论】:

  • 仅适用于“File'sOwner”,不适用于“View”
  • 尝试将自定义类的名称设置为此处的值。我相信这是缺失的部分。
  • 你确定吗?还没有看到有人建议在那里设置自定义类
  • 本人不使用楼主。您可以将出口绑定到视图本身,然后使用 nil 所有者。显然,仅适用于这些独立视图。
【解决方案2】:

您应该将正确的 TranslationInfoWindow.xib 类设置为 IB 中的 TranslationInfoWindow 类型。

【讨论】:

  • 尝试遍历笔尖,并选择正确的笔尖,如果类型与您的班级相同...而不是选择第一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多