[英]UITableView at iOS
我在Swift 4.0遇到問題。 我已經在TableView中添加了AppleMap,當我觸摸地圖時,需要在該位置添加圖釘。 但是當touchesBegan開始時,它不會在地圖上添加圖釘。
@IBOutlet var tableView: UITableView!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath) as? HimBasvuruCell
for touch in touches {
let touchPoint = touch.location(in: cell?.mapView)
let location = cell?.mapView.convert(touchPoint, toCoordinateFrom: cell?.mapView)
print ("\(location!.latitude), \(location?.longitude)")
addAnnotation(location: location!)
}
}
我已經構建了一個項目,並對其進行了測試,將其拖到ViewController中,並在cell上添加了一個mapView。 您的細胞班級的拳頭應該像:
import UIKit
import MapKit
class TableViewCell: UITableViewCell, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
// define a function if you need to use map info in ViewController
var mapAction: (() -> ())?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
mapView.delegate = self
mapAction()
}
override func setSelected(_ selected: Bool, animated: Bool ) {
super.setSelected(selected, animated: animated)
let gestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(handleTap))
gestureRecognizer.delegate = self
mapView.addGestureRecognizer(gestureRecognizer)
}
@objc func handleTap(gestureReconizer: UILongPressGestureRecognizer) {
let location = gestureReconizer.location(in: mapView)
let coordinate = mapView.convert(location,toCoordinateFrom: mapView)
// Add annotation:
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
}
}
那么您的tableView應該在ViewController類中確認其委托
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
cell.mapAction = { [unowned self] in
print("\(cell.mapView.annotations[indexpath.row])")
}
return cell
}
}
我希望這有幫助。
當您使用表格視圖時,touchesBegan將不會被調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.