如何在 Swift 事件中更改 UIBarButtonItem 的功能

How to change the function of a UIBarButtonItem on event in Swift

我一直在关注 Let's Build That App 中的 Youtube 教程,使用 Google Maps SDK 逐步实现导航系统。我希望能够将编程生成的 'next' UIBarButtonItem 更改为最后一个地图位置上的 'done' 按钮,并使用它返回到之前的 ViewController

使用 Swift 进行此操作的正确方法是什么?

https://www.youtube.com/watch?v=8wPjCdDn2wo

我的代码:

    navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "Next",
            style: .plain,
            target: self,
            action: #selector(nextLocation)
        )
}

func nextLocation() {

    if currentDestination == nil {
        currentDestination = destinations.first


    }
    else {

        if let index = destinations.index(of: currentDestination!), index < destinations.count - 1{
            currentDestination = destinations[index + 1]

        }
    }

    setMapCamera()
}

private func setMapCamera() {
    CATransaction.begin()
    CATransaction.setValue(2, forKey: kCATransactionAnimationDuration)
    mapView?.animate(to: GMSCameraPosition.camera(withTarget: currentDestination!.location, zoom: currentDestination!.zoom))

    CATransaction.commit()
    let marker = GMSMarker(position: currentDestination!.location)
    marker.title = currentDestination?.name
    marker.map = mapView

}

/* My incorrect code */

func lastLocation() {

    if currentDestination == destinations.last {
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "Finish",
            style: .plain,
            target: "myItinerary",
            action: #selector(lastLocation)
        )
    }
}

希望对您有所帮助: 第一:检测最后一个位置或点击最后一个位置后的条形按钮,将条形按钮标签更改为 "Done"。然后在按钮 "Done" 单击后将操作设置为按钮再次更改为 "Next" 并将目标计数器设置为第一个值。

func next() {

   if currentDestination == nil {
       currentDestination = destinations.first
   } else {
       if let index = destinations.index(of: currentDestination!), index < destinations.count - 1 {
           currentDestination = destinations[index + 1]
       }
       else {
           // After last Location change button title to "Done"
           navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(lastLocation))
       }

   }
   setMapCamera()
}

func lastLocation() {
    currentDestination = destinations.first // Set destinations counter to First value 
    // Change Title of Bar Button
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(ViewController.next as (ViewController) -> () -> ()))
} 

如果您想向后移动(反向),则:

func lastLocation() {
    currentDestination = destinations.last
    destinations = destinations.reversed()
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(ViewController.next as (ViewController) -> () -> ()))
}