ios - TableViewCell 中用于打开 map 应用的按钮

标签 ios swift xcode uitableview

我有一个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 变量链接到我拥有的结构,该结构收集有关站点的各种数据,包括纬度和经度。这很好用,当我从我的 Tableview 中选择一行时,它会打开苹果 map 并绘制从当前位置到该行位置的路线。

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

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

最佳答案

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

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

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
    }
    

关于ios - TableViewCell 中用于打开 map 应用的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42813878/

相关文章:

xcode - Xcode 8.1 中的每个文件编译器标志

ios - 将 XCode 命令行 C++ 程序转换为 Cocoa Mac App OSX 程序

ios - 在 React Native 中居中 PickerIOS

ios - NSDecimal 等于 NSDecimalNumber 值?

ios - UIPanGestureRecognizer 为什么以及如何使 UISwipeGestureRecognizer 静音,而 UITapGestureRecognizers 默认情况下不会相互静音?

ios - 在文件之间快速传递数据

ios - Alamofire 蜂窝网络 "Error Domain=NSURLErrorDomain Code=-1009"

android - 将 Firebase 用于 iOS 和 Android 应用

swift - Xcode 10 存档应用程序无法在安装了 Xcode 9 或更早版本的 Mac 上运行 : DYLD, [0x4] 符号丢失?

c++ - 适用于 mac 的免费 c++ 编译器不使用 xcode