In a storyboard, how do I make a custom cell for use with multiple controllers?

問題:

I'm trying to use storyboards in an app I'm working on.我正在嘗試在我正在開發的應用程序中使用故事板。 In the app there are Lists and Users and each contains a collection of the other (members of a list, lists owned by a user).在應用程序中有列表用戶,每個都包含另一個集合(列表的成員,用戶擁有的列表)。 So, accordingly, I have ListCell and UserCell classes.因此,相應地,我有ListCellUserCell類。 The goal is to have those be re-usable throughout the app (ie, in any of my tableview controllers).目標是讓它們在整個應用程序中(即,在我的任何 tableview 控制器中)可重複使用。

That's where I'm running into a problem.這就是我遇到問題的地方。

How do I create a custom tableview cell in the storyboard that can be re-used in any view controller?如何在故事板中創建可以在任何視圖控制器中重複使用的自定義 tableview 單元格?

Here are the specific things I've tried so far.以下是我迄今爲止嘗試過的具體事情。

  • In Controller #1, added a prototype cell, set the class to my UITableViewCell subclass, set the reuse id, added the labels and wired them to the class's outlets.在控制器 #1 中,添加了一個原型單元,將類設置爲我的UITableViewCell子類,設置重用 ID,添加標籤並將它們連接到類的插座。 In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before.在 Controller #2 中,添加了一個空的原型單元格,將其設置爲與以前相同的類並重用 id。 When it runs, the labels never appear when the cells are shown in Controller #2.當它運行時,當單元格顯示在控制器 #2 中時,標籤永遠不會出現。 Works fine in Controller #1.在控制器 #1 中工作正常。

  • Designed each cell type in a different NIB and wired up to the appropriate cell class.在不同的 NIB 中設計每種細胞類型並連接到適當的細胞類別。 In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class.在故事板中,添加了一個空的原型單元格並設置其類並重用 id 來引用我的單元格類。 In controllers' viewDidLoad methods, registered those NIB files for the reuse id.在控制器的viewDidLoad方法中,爲重用 ID 註冊這些 NIB 文件。 When shown, cells in both controllers were empty like the prototype.顯示時,兩個控制器中的單元格都像原型一樣是空的。

  • Kept prototypes in both controllers empty and set class and reuse id to my cell class.將兩個控制器中的原型保持爲空並設置類並將 id 重用於我的單元類。 Constructed the cells' UI entirely in code.完全在代碼中構建單元格的 UI。 Cells work perfectly in all controllers.單元格在所有控制器中都能完美運行。

In the second case I suspect that the prototype is always overriding the NIB and if I killed the prototype cells, registering my NIB for the reuse id would work.在第二種情況下,我懷疑原型總是覆蓋 NIB,如果我殺死了原型單元,則將我的 NIB 註冊爲重用 ID 會起作用。 But then I wouldn't be able to setup segues from the cells to other frames, which is really the whole point of using storyboards.但是我將無法設置從單元格到其他幀的轉場,這纔是使用故事板的真正意義所在。

At the end of the day, I want two things: wire up tableview based flows in the storyboard and define cell layouts visually rather than in code.歸根結底,我想要兩件事:在故事板中連接基於 tableview 的流,並以視覺方式而不是在代碼中定義單元格佈局。 I can't see how to get both of those so far.到目前爲止,我不知道如何獲得這兩個。


解決方案:

參考一: https://en.stackoom.com/question/cnIX
參考二: https://stackoom.com/question/cnIX
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章