2016-09-18 79 views
1

我有兩個UIViewControllers之間的分段控制許可證切換。信息視圖和列表視圖(TableView)。 我想使用第一個UIViewController作爲我的TableView的第一個單元格(即在另一個段上)。 有一種方法可以將UIViewController轉換爲單元格或將其用作TableView的單元格?使用UIViewController作爲TableView單元格

+0

是的,你可以添加VC的視圖的內容查看的子視圖細胞。您還需要將VC作爲子VC添加到某個父VC。使用自動佈局來定位VC視圖。 – Sajjon

+0

謝謝。我如何添加我的InfoViewController作爲一個孩子?爲什麼父母。這部分我沒有做得很好。 –

回答

1

以您自己的方式使用此代碼。在這裏,我們將控制器視圖添加爲單元格的子視圖並使用自動佈局進行正確管理。你只需要通過理解來使用代碼。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath) 
    cell.layoutIfNeeded() 

    let infoVC = self.storyboard.instantiateViewControllerWithIdentifier("InfoVC") 
    self.addChildViewController(infoVC) 
    cell.contentView.addSubview(infoVC.view) 

    infoVC.view.translatesAutoresizingMaskIntoConstraints = false 
    cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0)) 
    cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0)) 
    cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)) 
    cell.contentView.addConstraint(NSLayoutConstraint(item: infoVC.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)) 

    infoVC.didMoveToParentViewController(self) 
    infoVC.view.layoutIfNeeded() 
} 
+2

這段代碼假設擁有UITableView的VC是DataSource – Sajjon

+0

我剛剛回答了你建議的@Sajjon,因爲我通過閱讀提問者想要做什麼也有同樣的想法。如果有任何錯誤,您可以更正答案。 –

+0

這似乎工作。但是我會努力的。 只是讓我問你一件事。我的tableview的其他單元格有不同的infoVC大小。我該如何處理? 例如...我的InfoVC的高度爲300,而我的其他單元格的高度爲70. –

0

好吧,我會推薦將創建一個自定義UITableViewCell有自己的筆尖文件,並從筆尖加載它。

這可以比對UITableViewSection增加/刪除。 Cell自身可以用你想要的任何方式在UI Builder中進行設計。你可以把文學作品放入你喜歡的單元格中。

這裏是一個簡短的教程如何待辦事項這樣: using-nib-xib-files

一個問題到問題都可以在這裏找到: Custom UITableViewCell from nib in Swift

+0

我可以這樣工作。問題是我已經有了我的佈局和故事板中的所有約束。有一種方法可以將它「轉換」爲一個nib(或xib)文件? –

+0

對不起,告訴你,但我認爲沒有自動方式待辦事項。我認爲你可能能夠將東西複製到nib/xib文件中。我認爲這將是一個乾淨的解決方案來創建一個像這樣的自定義單元格。而且它可以很容易維護,而且你不必在代碼中設置限制。 您可以嘗試使用ContainerViewController將另一個故事板加載到xib/nib單元中。 (這肯定是一個骯髒的黑客,我wouldnt推薦它!)https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html – BennX

相關問題