我正在尝试使用带textField
的警报控制器,使用mapView
作为标题创建textField
注释。我可以打印我创建的所有常量,但注释不起作用。当我在alertAction
之外使用注释代码时,它工作正常,但我无法获得textField
输入。我究竟做错了什么?
override func viewDidLoad() {
super.viewDidLoad()
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)
}
func longpress(gestureRecognizer: UIGestureRecognizer) {
let alert = UIAlertController(title: "New Place", message: "Enter a name", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Name"
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) in
if let tempPlace = alert.textFields?[0].text {
let place = tempPlace
let touchpoint = gestureRecognizer.location(in: self.map)
let coordinate = self.map.convert(touchpoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()
let latitude = coordinate.latitude
let longitude = coordinate.longitude
annotation.title = place
annotation.subtitle = "Lat " + (String(format: "%.2f", latitude) + " Lon " + String(format: "%.2f", longitude))
annotation.coordinate = coordinate
self.map.addAnnotation(annotation)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (UIAlertAction) in
}
alert.addAction(okAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
答案 0 :(得分:0)
只需在UIAlertController演示之前存储触摸点并在UIAlterAction中使用它,因为当长按时警报弹出/存在时,它无法保存/获取触点,为什么UIAlterAction内的触点始终为0,0。
func longpress(gestureRecognizer: UIGestureRecognizer) {
let touchpointtemp = gestureRecognizer.location(in: self.map_home)
let alert = UIAlertController(title: "New Place", message: "Enter a name", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Name"
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) in
if let tempPlace = alert.textFields?[0].text {
let place = tempPlace
let touchpoint = touchpointtemp
let coordinate = self.map_home.convert(touchpoint, toCoordinateFrom: self.map_home)
print(coordinate)
let annotation = MKPointAnnotation()
let latitude = coordinate.latitude
let longitude = coordinate.longitude
annotation.title = place
annotation.subtitle = "Lat " + (String(format: "%.2f", latitude) + " Lon " + String(format: "%.2f", longitude))
annotation.coordinate = coordinate
self.map_home.addAnnotation(annotation)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (UIAlertAction) in
}
alert.addAction(okAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}