我一直试图解决这个问题好几天,并且没有多少运气:(
我想要做的是在另一个ViewController中已经存在的XIB实例(称为BottomNav)中设置变量,称为" curX"。我最接近以下内容:
class Util: NSObject {
class func loadNib() {
let nib: BottomNav = Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)!.first as! BottomNav
nib.curX = 10
}
}
这是BottomNav类:
class BottomNav: UIView {
@IBOutlet var view: UIView!
@IBOutlet weak var homeBtn: UIView!
@IBOutlet weak var scroller: UIScrollView!
@IBOutlet weak var scrollerContent: UIView!
var curX = 32
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
self.addSubview(self.view)
}
}
这会在没有警告的情况下通过编译器,但是当它运行时,我得到一个"这个类不是密钥值编码兼容的密钥"错误。这通常出现在有一个不再存在的插座时,但绝对不是这样,我已经使用已经在应用程序上的多个XIB测试了它,并且首先加载没有问题通过故事板。我只用" loadNibNamed"。
得到这个错误我是否在正确的道路上?我的想法可能是我的Util类无法访问Bundle或其他东西?
答案 0 :(得分:4)
class BottomNav: UIView {
@IBOutlet var view: UIView!
@IBOutlet weak var homeBtn: UIView!
@IBOutlet weak var scroller: UIScrollView!
@IBOutlet weak var scrollerContent: UIView!
var curX = 32
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
guard let content = view else { return }
content.frame = self.bounds
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.addSubview(content)
}
}
在调用实例时,请尝试以下操作。
let instance = BottomNav()
instance.curX = 30
答案 1 :(得分:2)
Swift 3.0
我认为你可以从中获得解决方案。一切顺利
var view: UIView!
override init(frame: CGRect) {
// call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
// call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
}
// MARK: - UI setup
func xibSetup() {
let nib = UINib(nibName: "BottomNav", bundle: nil)
view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}