UIPickerView перепрыгивает значения в массиве при прокрутке - PullRequest
0 голосов
/ 09 июня 2018

У меня проблемы с UIPickerView.У меня есть приложение, в котором inputView UITextField установлен как UIPickerView.Когда он появляется, все в порядке.Название строки правильное, но когда я прокручиваю вниз до следующего элемента, он каким-то образом пропускает несколько значений массива и останавливается на неправильном значении.В конце заголовок не равен его фактическому значению.

Вот мой код:

class ViewController: UIViewController {

...

// MARK: - Race outlet
@IBOutlet weak var raceTextField: UITextField!

// MARK: - "Purchased" column outlets
@IBOutlet weak var purchasedStrTextField: UITextField!
@IBOutlet weak var purchasedDexTextField: UITextField!
@IBOutlet weak var purchasedConTextField: UITextField!
@IBOutlet weak var purchasedIntTextField: UITextField!
@IBOutlet weak var purchasedWisTextField: UITextField!
@IBOutlet weak var purchasedChaTextField: UITextField!

...

// MARK: - "Actual" column outlets
@IBOutlet weak var actualStrLabel: UILabel!
@IBOutlet weak var actualDexLabel: UILabel!
@IBOutlet weak var actualConLabel: UILabel!
@IBOutlet weak var actualIntLabel: UILabel!
@IBOutlet weak var actualWisLabel: UILabel!
@IBOutlet weak var actualChaLabel: UILabel!

...

// MARK: - Constants
let pickerView = UIPickerView()

// MARK: - Variables
var raceArray = [Race]()
var selectedTextField: Int!

// MARK: - Lifecicle
override func viewDidLoad() {
    super.viewDidLoad()

    configurePickerView()
    congigureTextFields()
    createRaces()

...
}

...

// MARK: - Methods

func createRaces() {
    let human = Race(str: 0, dex: 0, con: 0, int: 0, wis: 0, cha: 0,
                     raceDesrciption: "Human (add +2 to any one ability)", raceMod: true)

    let elf = Race(str: 0, dex: 2, con: -2, int: 2, wis: 0, cha: 0,
                   raceDesrciption: "Elf", raceMod: false)

    let halfElf = Race(str: 0, dex: 0, con: 0, int: 0, wis: 0, cha: 0,
                       raceDesrciption: "Half-Elf (add +2 to any one ability)", raceMod: true)

    let dwarf = Race(str: 0, dex: 0, con: 2, int: 0, wis: 2, cha: -2,
                     raceDesrciption: "Dwarf", raceMod: false)

    let hafling = Race(str: -2, dex: 2, con: 0, int: 0, wis: 0, cha: 2,
                       raceDesrciption: "Hafling", raceMod: false)

    let gnome = Race(str: -2, dex: 0, con: 2, int: 0, wis: 0, cha: 2,
                     raceDesrciption: "Gnome", raceMod: false)

    let halfOrc = Race(str: 0, dex: 0, con: 0, int: 0, wis: 0, cha: 0,
                       raceDesrciption: "Half-Orc (add +2 to any one ability)", raceMod: true)

    let other = Race(str: 0, dex: 0, con: 0, int: 0, wis: 0, cha: 0,
                     raceDesrciption: "Other", raceMod: true)

    raceArray.append(human)
    raceArray.append(elf)
    raceArray.append(halfElf)
    raceArray.append(dwarf)
    raceArray.append(hafling)
    raceArray.append(gnome)
    raceArray.append(halfOrc)
    raceArray.append(other)
}

/// Set parameters for specific race
func setDefaultPoints(_ selectedRace: String) {
    for item in raceArray {
        if selectedRace == item.raceDesrciption {
            raceModeStrTextField.text = "\(item.str!)"
            raceModeDexTextField.text = "\(item.dex!)"
            raceModeConTextField.text = "\(item.con!)"
            raceModeIntTextField.text = "\(item.int!)"
            raceModeWisTextField.text = "\(item.wis!)"
            raceModeChaTextField.text = "\(item.cha!)"

            setActualPointsForRace(item)
            switchRaceModTextTield(item.editableRaceMod)
        }
    }
}

/// Update "Actual points" labels
func setActualPointsForRace(_ race: Race) {
    actualStrLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.str)"
    strLabel.text = actualStrLabel.text

    actualDexLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.dex)"
    dexLabel.text = actualDexLabel.text

    actualConLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.con)"
    conLabel.text = actualConLabel.text

    actualIntLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.int)"
    intLabel.text = actualIntLabel.text

    actualWisLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.wis)"
    wisLabel.text = actualWisLabel.text

    actualChaLabel.text = "\(Int(lowPoweredValueLabel.text!)! - race.cha)"
    chaLabel.text = actualChaLabel.text
}

func setTotalPointsWith(_ points: Int) {
    let currentValue = Int(totalPointValueLabel.text!)!
    totalPointValueLabel.text = "\(currentValue + points)"
}
}

Вот мой UIPickerView код:

extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {

func configurePickerView() {
    pickerView.delegate = self
    pickerView.dataSource = self
    pickerView.showsSelectionIndicator = true
}

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if selectedTextField == 1 {
        print(raceArray.count)
        return raceArray.count

    } else {
        print(purchaseValues.count)
        return purchaseValues.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    switch selectedTextField {
    case 1:
        raceTextField.text = raceArray[row].raceDesrciption
        return raceArray[row].raceDesrciption

    case 2:
        purchasedStrTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    case 3:
        purchasedDexTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    case 4:
        purchasedConTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    case 5:
        purchasedIntTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    case 6:
        purchasedWisTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    case 7:
        purchasedChaTextField.text = "\(purchaseValues[row].0)"
        return "\(purchaseValues[row].0)"

    default:
        print("no value")
    }

    return nil
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    switch selectedTextField {
    case 1:
        setDefaultPoints(raceArray[row].raceDesrciption)

    case 2:
        actualStrLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    case 3:
        actualDexLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    case 4:
        actualConLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    case 5:
        actualIntLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    case 6:
        actualWisLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    case 7:
        actualChaLabel.text = "\(purchaseValues[row].0)"
        setTotalPointsWith(purchaseValues[row].1)

    default:
        print("no value")
    }
}
}

TextFields настроить:

extension ViewController: UITextFieldDelegate {

func congigureTextFields() {
    raceTextField.inputView = pickerView
    purchasedStrTextField.inputView = pickerView
    purchasedDexTextField.inputView = pickerView
    purchasedConTextField.inputView = pickerView
    purchasedIntTextField.inputView = pickerView
    purchasedWisTextField.inputView = pickerView
    purchasedChaTextField.inputView = pickerView

    raceTextField.delegate = self
    purchasedStrTextField.delegate = self
    purchasedDexTextField.delegate = self
    purchasedConTextField.delegate = self
    purchasedIntTextField.delegate = self
    purchasedWisTextField.delegate = self
    purchasedChaTextField.delegate = self
    raceModeStrTextField.delegate = self
    raceModeDexTextField.delegate = self
    raceModeConTextField.delegate = self
    raceModeIntTextField.delegate = self
    raceModeWisTextField.delegate = self
    raceModeChaTextField.delegate = self
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    selectedTextField = textField.tag
    pickerView.reloadAllComponents()
}
}

И purchaseValues массив:

let purchaseValues = [
(7, -4),
(8, -2),
(9, -1),
(10, 0),
(11, 1),
(12, 2),
(13, 3),
(14, 5),
(15, 7),
(16, 10),
(17, 13),
(18, 17)
]

1 Ответ

0 голосов
/ 10 июня 2018

Как сказал @rmaddy: «... единственная цель titleForRow. Это единственная задача - сообщить представлению сборщика, какой заголовок использовать для запрашиваемой строки».- здесь я ошибся.Большое спасибо!

...