2015-10-02 30 views
0

我正在處理用戶有5個文本字段來輸入數據的項目。 「計算」按鈕根據用戶輸入計算所需的計算。 我的解決方案是創建5個IBOutlet UITextField並將它們連接到一個xib文件中。每個文本字段都使用以下代碼處理基於輸入的事件。有人能告訴我一種解決問題的有效方法嗎?有人能告訴我一個更有效的方式來處理多個文本字段代表?

- (BOOL)textFieldShouldReturn:(UITextField *)textField{ 

if(textField == self.numberOfNightsTF){ 
    self.numberOfNights = [self.numberOfNightsTF.text intValue]; 
    NSLog(@"The number of nights is set to %.d days", self.numberOfNights); 

} 
else if(textField == self.nightlyChargeTF){ 
    self.nightChargeCost = [self.nightlyChargeTF.text floatValue]; 
    NSLog(@"The cost of charge per night is set to %.2f$", self.nightChargeCost); 
} 

else if(textField == self.roomServiceTF){ 
    self.roomServiceCost = [self.roomServiceTF.text floatValue]; 
    NSLog(@"The additional room service cost is set to %.2f$", self.roomServiceCost); 
} 

else if(textField == self.telephoneTF){ 
    self.telephoneCost = [self.telephoneTF.text floatValue]; 
    NSLog(@"The additional telephone service cost for telephone is set to %.2f$", self.telephoneCost); 
} 
else if(textField == self.miscCostTF){ 
    self.miscCost = [self.miscCostTF.text floatValue]; 
    NSLog(@"The miscellaneous is now set to %.2f$", self.miscCost); 
} 
[textField resignFirstResponder]; 
return YES; 

}

+0

標題可以重寫,但這個問題顯示足夠的研究和代碼,以保持開放。 –

回答

0

您已經處理過這種方式沒有真正的不足,它與其他任何方法一樣好。這種方法唯一真正的問題是,當多次應用(這種方法)時,會導致ViewController類臃腫。

隨着您在面向對象環境中獲得更多經驗,您將瞭解到MVC,並且您在此處修改的狀態變量將是模型對象的屬性而非自身(假設此代碼位於某個ViewController中),因此消息可能是self.model.telephoneCost = .....等

0

有幾個解決方案,這將有助於清理。

最簡單的方法是在當前正在使用的函數中使用switch語句,這對於可讀性有一定幫助。

另一種選擇是創建一個類別,允許您在調用每個委託方法時設置回調塊。這些都是很容易編寫和已經存在Github上的一些例子:UITextField+Blocks

0

我會建議BlocksKit因爲它增加了塊一堆其他類的支持爲好,如UIAlertView中,韓國國際志願者組織等

如果您想要充分反應式,ReactiveCocoa是一個非常全面的框架,也提供了類似的功能。

BlocksKit更輕巧,如果你習慣於阻止風格編程,閱讀起來相當容易,而ReactiveCocoa由於其陡峭的學習曲線需要更大的承諾(但也提供了一些很棒的功能,如@strongify和@weakify來協助保留塊的問題)。

相關問題