【发布时间】:2018-05-03 02:44:54
【问题描述】:
我见过很多类似的问题,但很多都不是最新的,也没有解决我的问题。
我有一个自定义 Xib 和类,CardView。当我尝试在代码中实例化它时,我得到Could not cast value of type 'UIView' to 'CardView'。
类如下:
class CardView: NibView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var flipButton: UIButton!
@IBOutlet weak var playButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("CardView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
NibView 是一个自定义超类,看起来像:
class NibView: UIView {
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
// Setup view from .xib file
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Setup view from .xib file
xibSetup()
}
}
private extension NibView {
func xibSetup() {
backgroundColor = UIColor.white
view = loadNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Adding custom subview on top of our view
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|",
options: [],
metrics: nil,
views: ["childView": view]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|",
options: [],
metrics: nil,
views: ["childView": view]))
}
}
extension UIView {
/** Loads instance from nib with the same name. */
func loadNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nibName = type(of: self).description().components(separatedBy: ".").last!
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView
}
}
这是我的文件检查器的屏幕截图,显示我将 File's Owner 自定义类设置为 CardView,这似乎是许多人的绊脚石
最后,我尝试将CardView 实例化如下:CardView().loadNib() as! CardView
【问题讨论】:
-
嘿,你有没有找到任何解决方案。我也面临同样的问题。