Dmar
Dmar

Reputation: 25

how to add a new element to a 2 component array for UIPickerview in swift

When I try and add the newItem with .count nothing shows up. when I use it replaces "car" and I don't see it in pickerview and also I need to scroll up and down a few times before the newItem shows up.

var picker1 = String()
var picker2 = String()

var pickerViewArray = [["Items", "car"], ["Action", "Turn", "Hit", "Pull", "Scrape"]]

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

    return pickerViewArray.count
}

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerViewArray[component][row]
}

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

    picker1 = pickerViewArray[0] [pickerView.selectedRow(inComponent: 0)] + ""
    picker2 = pickerViewArray[1] [pickerView.selectedRow(inComponent: 1)] + ""
}

func addItemsToArray () {
    stringWall = "Wall"        
    addItemAtIndex = pickerViewArray[0].count
    pickerViewArray[0].insert(newItem, at: addItemAtIndex)
    allRoomArray[arraySelector][wallButton] = stringWall

    pickingRooms()
    print(newItem)
}

Upvotes: 1

Views: 649

Answers (1)

antonio081014
antonio081014

Reputation: 3593

I don't think ppl do what you want in this way. Usually, I will create a UITableView with customized UITableViewCell to fulfill dynamic list. UIPickerView is quite predefined and not so much dynamic view.

While for your code, if you really need your UIPickerView be dynamic so badly, I will say

Add self.pickerView.setNeedsLayout() after you change your datasource, pickerViewArray for your case.

I tested it on XCode9 beta3, target on iOS 8.0, with Swift 3.

Upvotes: 1

Related Questions