2015-08-14 10 views
0

我有一个自定义单元格的可用视图。自定义单元格包含一个标签和两个按钮。 对于每个对象(标签,uibuttons),我从三个单独的数组中加载一个单独的值。从数组中加载自定义单元格值取决于用户在Swift中的选择

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] 

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

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

而且用户答复桔子与第三对象的细胞(对于的UILabel和两个uibuttons)被加载,这将导致在

橙哪个颜色?

深橙黄色

任何想法是极大的赞赏。

谢谢。

回答

1

我建议使用一个枚举和计算性能:

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 
} 

希望这有助于!

+0

非常感谢!我会尝试一下代码。首先想到的是 - 如果我在所有数组中有更多的选项,该怎么办?我每次都必须写个案吗? –

+0

如果你打算使用完全相同的标签和按钮,那么你会的。这就是说,通过这种方式进行设计,不需要太多的努力来添加新的选项。另外,如果此解决方案最终适合您的需求,请将我的答案标记为已接受。谢谢 – jnoor

+0

其实,现在我想到了,你可以在currentQuestion中使用didSet来总是调用update。 'var currentQuestion:Question = .WhichFruit {didSet {updateTitles()}}' - 查看修订后的答案 – jnoor

相关问题