我很難找到或想到一種可以存盤 textView 文本的方法。所以以后如果需要我可以將它傳回服務器。
我在 CustomCell UITableViewCell 中有一個 TextView。(我的表格視圖中有 2 個部分,每個部分都有一個自定義單元格,里面有一個 textView。)我需要以某種方式傳遞或保存用戶撰寫的文本,以便我可以提取該文本并將其發送到其他地方。每次我的“可重復使用”單元格中的文本被重復使用時,文本就會消失。我試圖將它保存在我的 customCell Swift 中,但我認為將文本保存在 customCell 檔案中并不是一個好主意。有人知道嗎?謝謝!
uj5u.com熱心網友回復:
第一步: 創建一個模型來填充單元格。
struct myModel {
let textFromCustomCell: string = ""
}
創建模型串列(以填充表格視圖)
第二步: 這有幾種方法可以做到,但我選擇了委托方法。
使您的 CustomCell 符合 UITextViewDelegate。
在 CustomCell 上保存一個 indexPath 變數:
var indexPath: 索引路徑?
在單元格上實作此 UITextview 委托方法:
func textViewDidChange(textView: UITextView)
在單元 awakeFromNib 中設定 textView 委托:
override func awakeFromNib() { super.awakeFromNib() textField.delegate = self}
5.創建一個CustomCellDelegate:
protocol CustomCellDelegate: AnyObject {
func cellTextDidChanges(indexPath: IndexPath, text: String)
}
需要時在單元格上呼叫此函式(可能在單元格上的 textViewDidChange 函式實作中)。
使包含 tableview 的 viewController 符合您的 CustomCellDelegate
在 viewController 上實作 CustomCellDelegate cellTextDidChanges 方法
在 cellTextDidChanges 實作中,您應該根據 indexPath 在您創建的模型串列上更新正確的模型文本。
請記住,第一次填充表格視圖時,文本將為空。
uj5u.com熱心網友回復:
在實作 tableView 時,我們應該確保有一些資料驅動的資料源。我的意思是創建一個模型來驅動你的 tableView 的 numberOfSections、numberOfRowsInSection 等。這樣你就可以在你的模型中有一個屬性來存盤 textView 的文本。
樣品型號:
struct TableViewModel {
// this will handle number of sections
var sections: [TableViewSectionModel]
}
struct TableViewSectionModel {
// this will handle number of rows
var rows: [TableViewRowModel]
}
struct TableViewRowModel {
var textViewText: String
/*
Other properties to fill in
*/
}
使用它,您可以像這樣創建資料模型:
var cell1 = TableViewRowModel(textViewText: "")
var cell2 = TableViewRowModel(textViewText: "")
var section1 = TableViewSectionModel(rows: [cell1, cell2])
var section2 = TableViewSectionModel(rows: [cell1, cell2])
var data = TableViewModel(sections: [section1, section2])
這將有助于更新模型中的屬性,您可以稍后將資料傳遞給后端。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421115.html
標籤:
上一篇:StackView-在ArrangedSubviews中交換按鈕
下一篇:查找兩個CGPoints之間的點
