我正在製作一個應用程序,讓學生在特定文本字段中輸入他們的成績。我希望他們輸入一個從0到100的數字。我只是想知道如何爲文本字段設置最大NUMBER值。設置文本字段的最大數字值
我假設我應該做出某種類型的動作,但我不確定使用什麼動作類型或代碼來設置最大值。
任何幫助將不勝感激:)!
我正在製作一個應用程序,讓學生在特定文本字段中輸入他們的成績。我希望他們輸入一個從0到100的數字。我只是想知道如何爲文本字段設置最大NUMBER值。設置文本字段的最大數字值
我假設我應該做出某種類型的動作,但我不確定使用什麼動作類型或代碼來設置最大值。
任何幫助將不勝感激:)!
如果您想展示有限數量的固定答案,您可以使用UIPickerView:http://sourcefreeze.com/ios-uipickerview-example-using-swift/。但是,如果你想有他們在一個文本框中輸入它,你可以驗證在textFieldDidEndEditing方法的輸入,像這樣:
func textFieldDidEndEditing(textField: UITextField) {
if textField.text.toInt() < 0 || textfield.text.toInt() > 100 {
//Here you can present an alert, change the input or clear the field.
}
}
另一種方法是使比分0當用戶輸入更多的東西時,消極和100比100。這允許你輸入分數得分像72.5:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
// Make sure the user entered a number
guard let score = Double(textField.text!) else {
let alert = UIAlertController(title: "Invalid Score", message: "Score must be a number from 0 to 100", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return false
}
if score < 0 {
textField.text = "0"
} else if score > 100 {
textField.text = "100"
}
return true
}
}
internal func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if ((self.inputTextField?.text)!.characters.count > 10 && range.length == 0)
{
return false
//return false // return NO to not change text
}else{
return true
}
}
注:導入文本字段UITextFieldDelegat。
你可以使用UIPickerView的值從0到100. – vacawama
@vacawama我會,但我是新來的swift和xcode,我真的不知道如何使用UIPickerView –