如何在swift中为文本字段赋值

时间:2016-07-30 12:08:19

标签: swift

如何将我的UITextField初始化为double而不是字符串?

我的应用用户使用我的IBoutlet

通过TextFields输入纬度和经度

但我无法将其转换为double以获取更多功能并保存在我的realm数据库中。我如何以及在何处转换它?

next_page_link2 = wait.until(
        EC.element_to_be_clickable((By.XPATH, '//div[contains(text(),"Show more comments")]')))

#now click this using execute_script
driver.execute_script("arguments[0].click()", next_page_link2)

然后在文件的下方再次调用func updateSpecimen()

@IBOutlet weak var latitudeTextField: UITextField!

@IBOutlet weak var longitudeTextField: UITextField!

func fillTextFields() {
    nameTextField.text = specimen.name
    latitude.TextField = specimen.latitude
    longitude.TextField = specimen.longitude

}


func updateSpecimen() {
let realm = try! Realm()
try! realm.write {
  self.specimen.name = self.nameTextField.text!
  self.specimen.longitude = self.longitudeTextField.text!
  self.specimen.latitude = self.latitudeTextField.text!
}

1 个答案:

答案 0 :(得分:4)

您可以将String转换为Double

if let text = self.Lat.text {
    let num = Double(text)
}

更新

class ViewController {

    @IBOutlet weak var latitudeTextField: UITextField!
    @IBOutlet weak var longitudeTextField: UITextField!

    func fillTextFields() {

        guard let
            latitudeText = latitudeTextField.text,
            latitude = Double(latitudeText),
            longitudeText = longitudeTextField.text,
            longitude = Double(longitudeText)
            else {
                // tell the user to fill the fields
                return
            }

        updateSpecimen(latitude, longitude:longitude)
    }

    func updateSpecimen(latitude: Double, longitude: Double) {
        // here you can use latidute and longitude
    }

}

更新2

您也可以使用这两个计算变量

var latitude: Double? {
    if let text = latitudeTextField.text {
        return Double(text)
    } else {
        return nil
    }
}

var longitude: Double? {
    if let text = longitudeTextField.text {
        return Double(text)
    } else {
        return nil
    }
}