根据用户在 Swift 中的选择从数组中加载自定义单元格值

Loading custom cell value from array depending on users choice in Swift

我有一个带自定义单元格的 uitableview。自定义单元格包含一个标签和两个按钮。 对于每个对象(标签、uibuttons),我从三个单独的数组中加载一个单独的值。

Label = [which fruit do you prefer?, Apple which color?, Orange which color?,    
orange which price?, Apple which price?]
Uibutton1 = [apple, green, deep orange, 5.99, 4.99]
Uibutton2 = [orange, red, yellow, 2.99, 1.99]

我的目标是将所有三个对象的第一个值加载到单元格中,然后根据用户的选择附加单元格值。

例如,如果第一个问题是 你喜欢哪种水果?

并且用户回复 oranges 加载了具有第三个对象(用于 uilabel 和两个 uibuttons)的单元格,这将导致

橙色是什么颜色?

深橙色 黄色

非常感谢任何想法。

谢谢。

我建议使用枚举和计算属性:

enum Question {
    case WhichFruit, AppleColor, OrangeColor, ApplePrice, OrangePrice
}
var currentQuestion: Question = .WhichFruit {
    didSet { updateTitles() }
}

var questionText: String {
    switch currentQuestion {
    case .WhichFruit: return "Which fruit do you prefer?"
    case .AppleColor, .OrangeColor: return "Which color?"
    case .ApplePrice, .OrangePrice: return "Which price?"
    }
}
var button1Text: String {
    switch currentQuestion {
    case .WhichFruit: return "Apple"
    case .AppleColor: return "Green"
    case .OrangeColor: return "Deep Orange"
    case .OrangePrice: return "5.99"
    case .ApplePrice: return "4.99"
    }
}
//continue for button2
//...

然后,加载初始数据:

override func viewDidLoad() {
    currentQueston = .WhichFruit
}
private func updateTitles() {
    questionLabel.text = questionText
    buttonOne.setTitle(button1Text, forState: UIControlState.Normal)
    buttonTwo.setTitle(button2Text, forState: UIControlState.Normal)
}

然后在按钮操作中,更新 currentQuestion 并再次调用 updateTitles。

func buttonOneWasPressed {
    switch currentQuestion {
    case .WhichFruit: //selected Apple
        currentQuestion = .AppleColor
    }
    //other cases here
}

希望对您有所帮助!