PickerView в ячейке TableView


#1

Добрый день. Помещаю в ячейку TableView PickerView на сториборде, в UITableViewCell в методе awakeFromNib() опеределяю делегаты

typePicker.dataSource = self
typePicker.delegate = self

все работает, но пропадают линии выбранной ячейки.
Как вернуть линии?


#2


#3

Попробуй реализовать все программно.
Я набросал по-быстрому. На сториборд кинул tableView (CitiesVC), в прототип ячейки (CitiesTVC) поле TextField. Ниже код 2-х классов:

1-й класс ячейки:

class CitiesTVC: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var textFieldOutlet: UITextField!

var citiesPV = UIPickerView()
var arrayCitiesPV: Array = [String]()
var arrayCities = ["PayPal","Payeer","Qiwi","Perfect Money"]


override func awakeFromNib() {
    super.awakeFromNib()
    citiesPV.delegate = self
    citiesPV.dataSource = self
    
    textFieldOutlet.inputView = citiesPV
    textFieldOutlet.textAlignment = .center
    addButtonPickerView()
    inputArray()
    textFieldOutlet.text = arrayCitiesPV[0]
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    
    // Configure the view for the selected state
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return arrayCitiesPV.count
}


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textFieldOutlet.text = arrayCitiesPV[row]
}

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    var label = UILabel(frame: CGRect(x: 0, y: 0, width: super.contentView.frame.size.width, height: super.contentView.frame.size.height))
    if let v = view {
        label = v as! UILabel
    }
    
    label.font = UIFont (name: "Helvetica Neue", size: 22)
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.numberOfLines = 2
    label.text = arrayCitiesPV[row]
    label.textAlignment = .center
    return label
}

func addButtonPickerView() {
    let toolBar = UIToolbar(frame: CGRect(x: 0, y: super.contentView.frame.size.height/6, width: super.contentView.frame.size.width, height: 40.0))
    toolBar.layer.position = CGPoint(x: super.contentView.frame.size.width/2, y: super.contentView.frame.size.height-20.0)
    toolBar.barStyle = UIBarStyle.blackTranslucent
    toolBar.tintColor = UIColor.white
    toolBar.backgroundColor = UIColor.black
    let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(CitiesTVC.donePressed))
    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: super.contentView.frame.size.width / 3, height: super.contentView.frame.size.height))
    label.font = UIFont(name: "Helvetica", size: 12)
    label.backgroundColor = UIColor.clear
    label.textColor = UIColor.white
    label.text = ""
    label.textAlignment = .center
    let textBtn = UIBarButtonItem(customView: label)
    toolBar.setItems([flexSpace,textBtn,flexSpace,doneButton], animated: true)
    textFieldOutlet.inputAccessoryView = toolBar
}

@objc func donePressed(sender: UIBarButtonItem) {
    textFieldOutlet.resignFirstResponder()
}

func inputArray() {
    arrayCitiesPV.removeAll()
    for item in arrayCities {
        arrayCitiesPV.append(item)
    }
}

}

2-й класс - viewControllera:

class CitiesVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
}

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

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

}


#4

Я так не хотел потому что не использую в ячейке toolBar, пользуясь методом didSelectRow, а при делегировании данные попадают в переменную, что в моем случае неправильно, поскольку я данные не только читаю из picker’a, но и записываю их в него. В любом случае спасибо за помощь, буду пробовать программно)


#5

В ячейке никакого toolBar’а нет. Здесь toolBar служит для добавления кнопки Done на PickerView.
В представленном коде Все так и происходим как Вам нужно: Данные записываются из переменной (массива) arrayCities в PickerView и Читаются из него в поле TextField которое находится в ячейке.

Т.е. можешь любой массив данных передать в PickerView.