简体   繁体   中英

Moving data between custom cells in a dynamic table in Swift

Firstly, apologies but I'm new to all of this (iOS Dev & Swift).

I have a number of custom cells that I dynamically load into a tableview. One of my cells is a data picker that, when the date is changed by the user, I want to send the updated data to one of the other cells but I'm stumped. Help please.

Since your cells are dynamically loaded into the table, it is not possible to address a specific cell directly. You should trying changing the underlying data source when the user chooses a date, and call table.reloadData()

Assuming the cells are loaded and visible, you can pass a reference of one cell to another, but you'll need to create a couple of methods within your custom cells.

In my case I have two custom cells, a cell named CellBirthday that contains a label named birthDateLabel, and a cell that contains a DatePicker named CellDatePicker. I want to update birthDateLabel every time the DataPicker value changes.

I'll first load the cells and store a reference of CellBirthday inside CellDatePicker, then when the date picker changes, I'll update the label value inside CellBirthday. Here is the relevant code fragment to load the two cells. In this example, I use the same name for both the cell tag and class name, for example CellBirthday is both the cell tag and the class name specified in the storyboard:

    let birthdayCell = tableView.dequeueReusableCell(withIdentifier: "CellBirthday") as! CellBirthday
    let datePickerCell = tableView.dequeueReusableCell(withIdentifier: "CellDatePicker") as! CellDatePicker
    datePickerCell.setBirthdayCell(BirthdayCell: birthdayCell)

And here are the custom classes:

class CellBirthday: UITableViewCell {

    @IBOutlet fileprivate weak var birthDateLabel: UILabel!

    var birthdayText: String? {
        didSet {
            birthDateLabel.text = birthdayText
        }
    }
}

class CellDatePicker: UITableViewCell {

    @IBOutlet fileprivate weak var datePicker: UIDatePicker!

    var birthdayCell: CellBirthday?

    func setBirthdayCell(BirthdayCell birthdayCell: CellBirthday) {
        self.birthdayCell = birthdayCell
    }

    func getDateString(FromPicker picker: UIDatePicker? = nil) -> String {

        var dateText: String = ""

        if picker != nil {
            let dateFormatter = DateFormatter()
            dateFormatter.setLocalizedDateFormatFromTemplate("MMMMdy")
            dateText = dateFormatter.string(from: picker!.date)
        }
        return dateText
    }

    @IBAction func datePickerValueChange(_ sender: UIDatePicker) {
        if birthdayCell != nil {
            birthdayCell!.birthdayText = getDateString(FromPicker: sender)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM