ios – 使用MapKit将视图居中显示到用户位置的按钮

前端之家收集整理的这篇文章主要介绍了ios – 使用MapKit将视图居中显示到用户位置的按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
MapKit中是否有专用按钮将摄像头集中在用户位置?或者我是否必须手动创建按钮并切换mapView.showsUserLocation = true?

解决方法

这种方式运行良好( Swift),您可以自定义按钮:
class YourViewController{
   ...
   @IBOutlet weak var mapView:MKMapView
   ...

   override func viewDidLoad() {
      super.viewDidLoad()
      ...
      addMapTrackingButton()
   }

   func addMapTrackingButton(){
      let image = UIImage(named: "trackme") as UIImage?
      let button   = UIButton(type: UIButtonType.System) as UIButton
      button.frame = CGRectMake(5,5,35,35)
      button.setImage(image,forState: .Normal)
      button.backgroundColor = .clearColor()
      button.addTarget(self,action: #selector(YourViewController.centerMapOnUserButtonClicked),forControlEvents:.TouchUpInside)
      self.mapView.addSubview(button)
   }

   func centerMapOnUserButtonClicked() {
      self.mapView.setUserTrackingMode( MKUserTrackingMode.Follow,animated: true)
   }
   ...
}

斯威夫特4:

func addMapTrackingButton(){
    let image = UIImage(named: "trackme") as UIImage?
    let button   = UIButton(type: UIButtonType.custom) as UIButton
    button.frame = CGRect(origin: CGPoint(x:5,y: 25),size: CGSize(width: 35,height: 35))
    button.setImage(image,for: .normal)
    button.backgroundColor = .clear
    button.addTarget(self,action: #selector(ViewController.centerMapOnUserButtonClicked),for:.touchUpInside)
    mapView.addSubview(button)
}

@objc func centerMapOnUserButtonClicked() {
    mapView.setUserTrackingMode(MKUserTrackingMode.follow,animated: true)
}
原文链接:https://www.f2er.com/iOS/328859.html

猜你在找的iOS相关文章