简体   繁体   中英

UIPickerView not showing calculated values correctly

I'm making a picker view to display a range of ages for users to pick.

The age ranges are:

  • 1 to 24 months old

  • 3 to 17 years old

I have all the logic and model done already and the app runs. The 1 to 24 months displays correctly but the values displayed in the years range is displaying incorrectly. It shows "3 years old" for the majority of the section and "4 years old" for the last three rows. Here is my code:

For some reason for the two else if statements I was given an error that I had to force unwrap the values (if someone could explain that'd be great). The third if statement is where the issue lies with the values.

Model

struct Age {
var ageMonths: String

static var all: [Age] {
    var ageArray = [Age]()
    for months in 1...24 { // adds months 1 through 24
        ageArray.append(Age(ageMonths: String(months)))
    }
    for months in Array(stride(from: 36, through: 204, by: 12)) { // adds years 3 through 17
        ageArray.append(Age(ageMonths: String(months)))
    }
    return ageArray
    }
}

View Controller

var age: Age?

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

        if Int(Age.all[row].ageMonths) == 1 {
            return Age.all[row].ageMonths + " month old"
        } else if Int(Age.all[row].ageMonths)! > 1 && Int(Age.all[row].ageMonths)! < 36 {
            return Age.all[row].ageMonths + " months old"
        } else if Int(Age.all[row].ageMonths)! >= 36 {
            return Age.all[row/12].ageMonths + " years old"
        }

    return ""
}

It looks like you just have a typo in the last if clause

    if Int(Age.all[row].ageMonths)! >= 36 {
        return Age.all[row/12].ageMonths + " years old"
    }

but it should be something like this (syntax might be sketchy, I'm just going on memory)

    if Int(Age.all[row].ageMonths)! >= 36 {
          let years: Float = Int(Age.all[row].ageMonths)/12
          return "\(years) years old"
    }

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