2017-02-20 46 views
-1

我試圖做一個UITableView,可以支持其中有不同的對象/元素。具體而言,這些元素是UITextFieldUISwitch原型UITableViewCell與其他對象(UITextField,UISwitch)

第一個問題:

元素顯示不出來。它們被放置在原型cell中,然後在我設置的class內構建。我已驗證cell安裝程序正在工作,因爲我可以更改每個cell上的文字,但cell中沒有任何元素。

這裏是構建我的電池現在的代碼:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    return 1 
} 



public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "EmailCell") 
    return cell 
} 

問題二(可能伴隨着第一可以解決):

我沒有在訪問信息的方式每個UITextField或每個UISwitch。我如何從存在的所有單元獲取這些信息?

在此先感謝您的幫助!

+0

被置'custom'原型細胞的風格? – vadian

+0

您必須顯示您用於「構建班級內單元格」的代碼。此外,您的故事板的屏幕截圖可能會有所幫助。 – naglerrr

+0

看起來你正在嘗試創建一個表單。你可以試試https://github.com/xmartlabs/Eureka – Sweeper

回答

1

你的代碼有很多錯誤。

對於自定義單元格,您需要實現自定義UITableViewCell子類。這裏是一個例子:

import UIKit  

class EmailCell: UITableViewCell { 

    @IBOutlet var customTextField: UITextField! 
    @IBOutlet var customSwitch: UISwitch! 

} 

之後,打開你的故事板,並選擇原型單元格。在Identity Inspector中將其更改爲EmailCell

enter image description here

還要確保你的UI元素連接到先前創建的@IBOutlet秒。如果您需要@IBOutlet的幫助,請參閱this StackOverflow post

enter image description here

在接下來的步驟,改變你的tableView(_:, cellForRowAt:)實現這樣的:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    let cell = tableView.dequeueReusableCell(withIdentifier: "EmailCell", for: indexPath) as! EmailCell 

    // Configure your custom ui elements however you want 
    cell.customTextField.text = "somestring" 
    cell.customSwitch.isOn = true 

    return cell 
} 
+0

這非常有效!非常感謝。有一件事,你知道我將如何檢測文本字段中的變化或在我的_view controller_類中切換嗎? (這是包含tableView設置的類) – TheMooCows237

0

確保您的細胞具有重用標識符和你在你的行單元格的數據源的索引使用方法

tableView.dequeueReusableCell(withIdentifier: -Your cell Id- , for: indexPath) as? -Your Cell Class- 

接下來您可以通過執行目標添加到您的文本字段/開關這在你的數據源的索引方法細胞爲行

cell.-your switch/text field-.addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged) 

,你應該繼承一個UITableView單元格添加屬性/ iboutlets

class YourTableViewCell: UITableViewCell { 

    @IBOutlet weak var yourSwitch: UISwitch! 

} 
+0

好的,我在cellForRowAt方法中添加了dequeueReusableCell。但是,我無法調用cell [switch/text field],因爲它不能識別原型單元格內有文本字段。我也不能將文本字段作爲插件鏈接,因爲XCode給我一個錯誤,說我不能將插口鏈接到重複內容。 – TheMooCows237