我试图在代码中模拟这个视图层次结构:
"scene"
"view Shop Main" -> `UIView`
"view shop scroll" -> `UIScrollView`
"ViewDetail" -> `UIView`
"Shop Connected Container" -> `UIView`
"Connected Shop" -> `UIView`
我想实例化倍数" Connected Shop"并将它们添加到" Shop Connected Container" 像这样:
"scene"
"view Shop Main" -> `UIView`
"view shop scroll" -> `UIScrollView`
"ViewDetail" -> `UIView`
"Shop Connected Container" -> `UIView`
"Connected Shop" -> `UIView`
"Connected Shop" -> `UIView`
"Connected Shop" -> `UIView`
我怎么能以编程方式执行此操作? 我有一个每个subView的自定义类和一个xib文件。 这就是我如何从代码中实例化子视图:
override func viewDidLoad() {
/*1*/ let vShopMain = NSBundle.mainBundle().loadNibNamed("viewShopMain", owner: self, options: nil).first as! viewShopMain
/*2*/ let vShopScroll = NSBundle.mainBundle().loadNibNamed("viewShopScroll", owner: vShopMain, options: nil).first as! viewShopScroll
/*3*/ let vDetail : UIView = NSBundle.mainBundle().loadNibNamed("viewDetail", owner: vShopScroll, options: nil).first as! viewDetail
//
//
/*4*/ let sConContainer : UIView = NSBundle.mainBundle().loadNibNamed("shopConnectedContainer", owner: vDetail, options: nil).first as! shopConnectedContainer
/*5*/ let cShop = NSBundle.mainBundle().loadNibNamed("connectedShop", owner: sConContainer, options: nil).first as! connectedShop
cShop.bannerTitle.text = "Shop Title"
vShopMain.addSubview(vShopScroll)
vShopScroll.addSubview(vDetail)
vDetail.addSubview(sConContainer)
sConContainer.addSubview(cShop)
self.view.addSubview(sConContainer)
也尝试了完全相同的结果:
let vShopMain = UINib(nibName: "viewShopMain", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! viewShopMain
let scroll = UINib(nibName: "viewShopScroll", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! viewShopScroll
let vDetail = UINib(nibName: "viewDetail", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! viewDetail
let sConContainer = UINib(nibName: "shopConnectedContainer", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! shopConnectedContainer
let cShop = UINib(nibName: "connectedShop", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! connectedShop
cShop.bannerTitle.text = "hola"
vShopMain.addSubview(scroll)
scroll.addSubview(vDetail)
vDetail.addSubview(sConContainer)
sConContainer.addSubview(cShop)
self.view.addSubview(sConContainer)
但"新"添加的视图位于另一个视图下方,这不是预期的行为,因为我从故事板中实例化现有视图,而不是创建新视图。
我遵循故事板层次结构的顺序。视图也与其自定义类链接,并且它们具有xib文件。但是,当我运行我的应用程序时,我遇到了这个奇怪的问题
我在这里做错了什么?请帮忙
答案 0 :(得分:0)
帮助您找出崩溃的原因。 loadNibNamed
返回一个对象数组,而不是单个视图。所以这肯定会崩溃
let vShopScroll = NSBundle.mainBundle().loadNibNamed("viewShopScroll", owner: self, options: nil) as! viewShopScroll
因为你假设它返回viewShopScroll
并强行打开它。正如你所说,你的第一行正在运行,因为你在那里采用了first
对象
let vShopMain = NSBundle.mainBundle().loadNibNamed("viewShopMain", owner: self, options: nil).first as! viewShopMain
同样适用于所有其他案例