我见过很多类似的问题,但很多都不是最新的,没有一个能解决我的问题。
我有一个自定义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的Owner自定义类设置为CardView,这似乎是许多的绊脚石
最后,我尝试将CardView
实例化如下:CardView().loadNib() as! CardView
老问题,但万一有人在这里:
我的问题是视图子类是fileprivate
。 IB显然不喜欢这样。
在你的UIViewController
中,当你创建CardView
的一个实例,而不是像CardView().loadNib() as! CardView
那样强制它时,你调用函数object_setClass(_, _)
来避免这个错误(来自Xcode 9)。
所以应该是这样的:
let myCardView = CardView().loadNib
object_setClass(myCardView, CardView.self)
view.addSubview(myCardView)
如果有人仍然有这个问题,我有同样的问题,我认为我们遵循相同的教程。
你已经在你的loadNib()
中打电话给xibSetup()
。我想你不必再打电话了。
所以不要使用
let myCardView = CardView().loadNib() as! CardView
我只是用
let myCardView = CardView()