簡體   English   中英

在表格視圖單元格之間移動的文本

[英]Text moving between table view cells

我有一個包含多個部分和每個部分中不同行數的表格視圖。

我創建了一個自定義表格視圖單元格。 該單元格有一個標簽和一個文本字段。

表格視圖中的每個單元格都使用相同的自定義單元格。

當我在文本字段中輸入一個值時,它會出現在其他一些文本字段以及其他行中。 有時文本從我輸入的文本字段中消失並出現在下面的行中。 當我上下滾動 tableview 時會發生這種情況。

這是我用於 cellForRowAt 的代碼

let cell = tableView.dequeueReusableCell(withIdentifier:   "LabelTextFieldTableViewCell", for: indexPath) as! LabelTextFieldTableViewCell
    for i in approachSection {
        if Int(i.row) == indexPath.row {
            cell.myLabel.text = i.name
            cell.myTextField.placeholder = cell.setPlaceholder(type: i.type!)
            if i.type != CustomFieldType.text.rawValue {
                cell.isInteger = true
            }
        }
    }
return cell

自定義單元格是

class LabelTextFieldTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myTextField: UITextField!

    var isInteger: Bool?
    var type: String!

    override func awakeFromNib() {
        super.awakeFromNib()
        myTextField.delegate = self
        myTextField.textAlignment = .right
        myTextField.borderStyle = .none


    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setPlaceholder(type: String) -> String {
        switch type {
        case CustomFieldType.count.rawValue:
            return "#"
        case CustomFieldType.time.rawValue:
            return "Time as 1234"
        case CustomFieldType.text.rawValue:
            return "Enter Text"
        default:
            return ""
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.textColor = .black
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        guard textField.text != "" else { return }

        if isInteger != nil {
            guard checkIfIntegers(str: textField.text!) != false else {
                print("Not all Integers")
                textField.textColor = .red
                return
            }
        }
    }

}

在您的單元子類中使用 prepareToReuse 方法。 在這里,您應該將所有值重置為默認值,並在相應的 cellForRowAtIndexPath 方法中將適當的值設置為單元格。

func prepareForReuse()

蘋果文檔

在你的LabelTextFieldTableViewCell類中編寫這個方法,我希望它能幫助你快樂編碼 =)

請確保您正確遵循此算法

  1. 首先,您將決定需要多少部分?
  2. 然后您將決定您需要的部分中有多少行
  3. 然后您將從單元格中分配您的數據源模型的每一行,因為您不必使用 for 循環。 Index.row 將為您完成這項工作。

注意:您可以在這些方法中使用 switch 語句來決定在哪個特定部分顯示多少行。

- tableView:cellForRowAtIndexPath: // required method

– tableView:numberOfRowsInSection: // required method

– numberOfSectionsInTableView:

– sectionIndexTitlesForTableView:

– tableView:sectionForSectionIndexTitle:atIndex:

– tableView:titleForHeaderInSection:

– tableView:titleForFooterInSection:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM