Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a pickerview when select a cell in a tableView

I have a tableView with 7 cells like this: enter image description here

I wanna trigger some events when you select a cell. For example, start editing the username when you tap the Username row. And pop up a picker view at the bottom with Male/Female selection inside when you tap the Gender row. As far as I know, I need to put those events inside this:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

}

But I have no idea how to accomplish this. Anyone has ideas? Thank you in advance.

like image 867
sekaisan Avatar asked Sep 27 '22 00:09

sekaisan


People also ask

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

How do I get IndexPath from cell Swift?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.


1 Answers

Basically, you can make each cell has its own picker view.

open class DatePickerTableViewCell: UITableViewCell {

  let picker = UIDatePicker()

  open override func awakeFromNib() {
    super.awakeFromNib()
    picker.datePickerMode = UIDatePickerMode.date
  }

  open override var canBecomeFirstResponder: Bool {
    return true
  }

  open override var canResignFirstResponder: Bool {
    return true
  }

  open override var inputView: UIView? {
    return picker
  }
  ...
}

And then in your didSelectRowAt, just make the cell becomeFirstResponder:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 if let cell = tableView.cellForRow(at: indexPath) as? DatePickerTableViewCell {
  if !cell.isFirstResponder {
    _ = cell.becomeFirstResponder()
  }
 }
}

You can check my library for detail: https://github.com/hijamoya/PickerViewCell

like image 86
Jam Avatar answered Nov 15 '22 08:11

Jam