Ios 尝试从文本字段获取纬度和经度时,无法转换类型的值
我的代码不起作用。 当用户输入纬度和经度时,它应该转到地图,但它只是抛出一个错误。它只有在我硬编码纬度和经度时才起作用Ios 尝试从文本字段获取纬度和经度时,无法转换类型的值,ios,swift,core-location,Ios,Swift,Core Location,我的代码不起作用。 当用户输入纬度和经度时,它应该转到地图,但它只是抛出一个错误。它只有在我硬编码纬度和经度时才起作用 import UIKit import MapKit class ViewController: UIViewController { @IBOutlet weak var Longitude: UITextField! @IBOutlet weak var Latitude_button: UITextField! @IBAction func s
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var Longitude: UITextField!
@IBOutlet weak var Latitude_button: UITextField!
@IBAction func showMeWhere(_ sender: Any)
{
//Defining destination
let latitude:CLLocationDegrees = Latitude_button
let longitude:CLLocationDegrees = Longitude
// let latitude:CLLocationDegrees = 39.048825
// let longitude:CLLocationDegrees = -120.981227
let regionDistance:CLLocationDistance = 1000;
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)]
let placemark = MKPlacemark(coordinate: coordinates)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "Test Location"
mapItem.openInMaps(launchOptions: options)
}
}
类型不正确 改变
let latitude:CLLocationDegrees=latitude\u按钮
到
Double(纬度按钮.text??)??0
与经度相同
let longitude:CLLocationDegrees=Double(longitude.text??)??0
还有,你的名字不太合适。应该像您的行上的latitudeButton
和longitude
一样让纬度:CLLocationDegrees=latitude_按钮
尝试将UITextField
类型的变量分配给CLLocationDegrees
类型的变量
您需要做的是从文本字段中获取文本,并尝试将其转换为数字,然后将该数字指定给变量
guard let latitude = CLLocationDegrees(Latitude_button.text!),
let longitude = CLLocationDegrees(Longitude.text!) else {
// show some sort message to the user that the values are invalid
return
}
以下是一些可能有助于您开始学习的内容,因为我一直在那里:
在Swift中,变量在camelCase
中,按照惯例,对于变量声明,远离snake\u case
和大写的
。我想为您的@IBOutlets
做一些类似的事情
@IBOutlet weak var longitudeField: UITextField!
@IBOutlet weak var latitudeField: UITextField!
UITextFields
中有string
,但在showmehere
方法中,您试图将UITextField
拉式分配给CLLocationDegrees
- 具有名为
text
的属性。这是你想要的,不是字段…你想要字段中的文本
- 是一个
typealias
用于Double
…因此,将字符串
转换为Double
之前的问题
以下是您的做法:
guard let latitude = Double(latitudeField.text),
let longitude = Double(longitudeField.text) else { return }
为什么要尝试将UITextField
变量分配给类型为CLLocationDegrees
的变量?无法将UITextField分配为CLLocationDegrees。尝试获取文本字段的文本,并将其转换为双精度,然后将该值指定给纬度或经度。