TableViewCell 中用于打开地图应用的按钮

Button in TableViewCell to go open Maps app

我有一个tableViewCell,里面有下面的代码

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var tr: newTracks!
    if inSearchMode {
        tr = filteredTrack[indexPath.row]
    } else {
        tr = items[indexPath.row]
    }
    let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
    let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
    mapItem.name = tr.name
    mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey :MKLaunchOptionsDirectionsModeDriving])
    }

tr 变量链接到我拥有的结构,该结构收集有关站点的各种数据,包括纬度和经度。这很好用,当我 select 来自我的 Tableview 的一行时,它会打开苹果地图并绘制从当前位置到该行位置的路线。

我想做的是在 tableviewcell 上实现一个名为 locate 的按钮,只有当您按下该按钮时,它才会打开苹果地图并绘制路线,如上所示。

有人可以帮助我了解如何实现按钮以及我的代码需要去哪里吗。

1) 创建自定义 class-:

class FruitTableViewCell: UITableViewCell {
@IBOutlet weak var buttonClick: UIButton!
}

2) 使用 cellForRowAt indexPath 方法-:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! FruitTableViewCell


cell.buttonClick.tag = 1; 
cell.buttonClick.addTarget(self, action:#selector(self.pressed), forControlEvents: .TouchUpInside)

    return cell
}

3) 使用所需代码实现目标方法-:

 func pressed(sender: UIButton!) {

 if (sender.tag == 1) 
     {
         var tr: newTracks!
        if inSearchMode {
            tr = filteredTrack[indexPath.row]
        } else {
            tr = items[indexPath.row]
        }
        let coordinate = CLLocationCoordinate2DMake(tr.lat,tr.lon)
        let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
        mapItem.name = tr.name
        mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey :MKLaunchOptionsDirectionsModeDriving])
     }

    }

一种方法是使用闭包。这是示例代码。

  1. 在 CustomTableViewCell 中,我们为按钮添加了完成和目标。按下按钮时,将调用完成。

class CustomTableViewCell: UITableViewCell {

@IBOutlet weak var button: UIButton!

var completion: ((Void) -> Void?)?

override func awakeFromNib() {
    button.addTarget(self, action: #selector(didTappedButton), for: .touchUpInside)
}

func didTappedButton() {
    if let completion = completion {
        completion()
    }
}

}

  1. 在您的 UITableView cellForRow 中,确保您投射到 CustomTableView 并分配补全 属性。在 cell.completion 闭包中,您可以调用任何您想要的操作。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
        cell.completion = {
            print("Button tapped")
        }
        return cell
    }