私はアドレスを含むセルを持つテーブルビューを持っており、ユーザーはそのアドレス(UILabel)をタップし、Appleのマップアプリケーションのその場所に移動できるようにします。マップにUILabelを接続する
ロケーションは配列なので、どのセルをどのように解析して、各セルの各位置に(タップして)Appleマップ上のその位置に移動できるかわかりません。
UPDATE:コードが今働いている、解決策は以下の存在である:
import UIKit
import MapKit
class FirstEventCell: UITableViewCell {
@IBOutlet weak var eventLocation: UILabel!
@IBAction func goToMaps(_ sender: UIButton) {
CLGeocoder().geocodeAddressString((eventLocation?.text)!, completionHandler: {(placemarks, error) in
if error != nil {
print("")
} else if placemarks!.count > 0 {
let placemark = placemarks![0]
let location = placemark.location
let coords = location!.coordinate
let coordinate = CLLocationCoordinate2DMake(coords.latitude,coords.longitude)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
mapItem.name = "Target location"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])
}
})
}
}
class EventsTableTableViewController: UITableViewController {
var locations = ["Washington, DC 20565", "1600 Pennsylvania Ave NW, Washington, DC 20500", "East Capitol St NE & First St SE, Washington, DC 20004"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath)
let eventLocation = locations[indexPath.row]
if let eventCell = cell as? FirstEventCell {
eventCell.eventLocation.text = eventLocation
}
return cell
}
didSelectRowAtIndexPathを定義する方法を知っていますか?私はこれがUITableViewに関する質問か、アドレスをMKMapViewのCLLocationに変換するかどうかはわかりません。 – dylanthelion
@ dylanthelionは、唯一ではないにしても一般的なやり方です。複数のテーブルを持つ場合、それらは両方とも関数への呼び出しを生成するので、それらを区別することができなければなりません。 – curt
@curt:おそらくこれは分かっていますが、同じビューで複数のテーブルを処理する正しい方法は、複数のUITableViewDelegatesとUITableViewDataSourcesを持つことです。 – dylanthelion