我有用于Celectial导航计算的应用程序,我已将代码textField.text转换为Double,但有时如果用户输入某些字段(例如“ 1.0”和“ 1”),应用程序崩溃,结果应用程序崩溃是因为't减去Int和Double,以确保我想限制用户只能输入十进制数字“ 1.0”。对我而言,最好的方法是编写如下代码:如果用户在按下完成按钮后自动输入“ 1”,然后添加“ .0”以获得1.0?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = "-1234567890."
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharactersSet = CharacterSet(charactersIn: string)
return allowedCharacterSet.isSuperset(of: typedCharactersSet)
}
func TextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = latDegTextField.text else { return true }
let count = text.count + string.count - range.length
return count == 2
}
答案 0 :(得分:1)
首先使用HERE中的此方法
Tgt_df_time_in_zone_detail = Tgt_df_view_time_in_zone_detail_dtaas.join(Tgt_df_individual_in_shift_tiz,
(Tgt_df_view_time_in_zone_detail_dtaas.id_individual == Tgt_df_individual_in_shift_tiz.id_individual)
& (Tgt_df_view_time_in_zone_detail_dtaas.timestamp_start >= Tgt_df_individual_in_shift_tiz.swipein)
& (Tgt_df_view_time_in_zone_detail_dtaas.timestamp_start <= Tgt_df_individual_in_shift_tiz.swipeout)
& (Tgt_df_view_time_in_zone_detail_dtaas.timestamp_end >= Tgt_df_individual_in_shift_tiz.swipein)
& (Tgt_df_view_time_in_zone_detail_dtaas.timestamp_end <= Tgt_df_individual_in_shift_tiz.swipeout)
, "left_outer")
然后在完成按钮的操作中添加以下内容:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text != "" || string != "" {
let res = (textField.text ?? "") + string
return Double(res) != nil
}
return true
}
当您输入@IBAction func btnDoneTapped(_ sender: Any) {
print(tf.text)
guard let obj = Double(tf.text!) else { return }
print(obj)
}
并按完成按钮时,1
将打印print(tf.text)
,而Optional("1")
将打印print(obj)
答案 1 :(得分:0)
使用此代码:-
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Will prevent user from entering space as first character
let enteredCharString = "\(textField.text ?? "")\(string )"
if enteredCharString.trimmingCharacters(in: .whitespaces).count == 0 {
return false
}
switch textField {
case txt_Ammount:
if txt_Ammount.text != "" || string != "" {
let res = (txt_Ammount.text ?? "") + string
return Double(res) != nil
}
default:
true
}
return true
}