ios - 设置导航栏按钮的目标

标签 ios swift uinavigationcontroller uinavigationbar

我尝试向导航 Controller 导航栏添加左按钮,但出现错误:

Cannot convert value of type 'NSObject -> () -> LocationViewController' to expected argument type 'AnyObject?'.

我浏览了其他SO问题,他们大部分都说要设置一个像这样的导航栏按钮。非常感谢任何帮助。

var leftAddBarButtonItem : UIBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(cancelButtonTapped))

我的行动:

func cancelButtonTapped(sender:UIButton) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

编辑: FullView Controller 代码

import UIKit
import MapKit

protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}

class LocationViewController: UIViewController {

let locationManager = CLLocationManager()
var resultSearchController:UISearchController? = nil
var selectedPin:MKPlacemark? = nil

var leftAddBarButtonItem : UIBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelButtonTapped")

func cancelButtonTapped(sender:UIButton) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

func setLocation() {
    if let selectedPin = selectedPin {
        let mapItem = MKMapItem(placemark: selectedPin)
        let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
        mapItem.openInMapsWithLaunchOptions(launchOptions)
    }
}

@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationItem.setLeftBarButtonItem(leftAddBarButtonItem, animated: true)

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()

    let locationSearchTable = storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTableViewController") as! LocationSearchTableViewController
    resultSearchController = UISearchController(searchResultsController: locationSearchTable)
    resultSearchController?.searchResultsUpdater = locationSearchTable

    let searchBar = resultSearchController!.searchBar
    searchBar.sizeToFit()
    searchBar.placeholder = "Search or Drop a Pin"
    navigationItem.titleView = resultSearchController?.searchBar

    resultSearchController?.hidesNavigationBarDuringPresentation = false
    resultSearchController?.dimsBackgroundDuringPresentation = true
    definesPresentationContext = true

    locationSearchTable.mapView = mapView
    locationSearchTable.handleMapSearchDelegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/
}

extension LocationViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if status == .AuthorizedWhenInUse {
        locationManager.requestLocation()
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegion(center: location.coordinate, span: span)
        mapView.setRegion(region, animated: true)
    }
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("error:: \(error)")
}
}

extension LocationViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
    // cache the pin
    selectedPin = placemark
    // clear existing pins
    mapView.removeAnnotations(mapView.annotations)
    let annotation = MKPointAnnotation()
    annotation.coordinate = placemark.coordinate
    annotation.title = placemark.name
    if let city = placemark.locality,
        let state = placemark.administrativeArea {
        annotation.subtitle = "\(city) \(state)"
    }
    mapView.addAnnotation(annotation)
    let span = MKCoordinateSpanMake(0.01, 0.01)
    let region = MKCoordinateRegionMake(placemark.coordinate, span)
    mapView.setRegion(region, animated: true)
}
}

extension LocationViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{
    if annotation is MKUserLocation {
        //return nil so map view draws "blue dot" for standard user location
        return nil
    }
    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    pinView?.pinTintColor = UIColor.orangeColor()
    pinView?.canShowCallout = true
    let smallSquare = CGSize(width: 60, height: 60)
    let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
    button.setBackgroundImage(UIImage(named: "PinButton2.jpg"), forState: .Normal)
    button.addTarget(self, action: #selector(LocationViewController.setLocation), forControlEvents: .TouchUpInside)
    pinView?.leftCalloutAccessoryView = button
    return pinView
}
}

最佳答案

我想说有一个错误..看起来你在任何函数旁边设置了 var leftAddBarButtonItem ... 行...将其设置在 viewDidLoad 中,然后它应该是工作。

如果您使用的是 swift 2.2,那么您的操作应该是 #selector(cancelButtonTapped(_:)) 否则只需使用“cancelButtonTapped:”...

关于ios - 设置导航栏按钮的目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995594/

相关文章:

ios - 如何检测 navigationController.view 中的触摸?

ios - Swift 中的语音转字符串

ios - 从 View Controller 中取出 collectionview 委托(delegate)和数据源

iOS 约束不允许使用乘数

iphone - 如何在 iPhone 中调整 UINavigationController 的大小?

ios - NativeScript Sidekick Publishing IOS 一直提示输入密码

ios - 从 UIScrollView 转发触摸 - UIButton 问题

ios - 搜索包含特定日期属性的核心数据数组的索引

iphone - UINavigationController 不显示 Root View Controller

iOS 7——navigationController 正在设置我的 UIScrollView 的 contentInset 和 ContentOffset