必须在MKAnnotationView之外点击标注气泡

时间:2015-08-04 00:35:31

标签: swift

我被迫通过子视图向MKAnnotationView添加图像,因为显然我不能将图像的maskToBounds属性设置为true,而不必将canShowCallout设置为false。以下是涵盖此问题的问题:Swift - setting rounded corners to annotation view image我不确定要配置什么,以便允许用户点按图像的中心以显示标注气泡。我已经搞乱了centerOffset,calloutOffset和锚点。这是我的代码:

extension MapViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if let annotation = annotation as? Food {
        if annotation == mapView.userLocation {
            return nil
        }
        let identifier = "pin"
        var view: MKAnnotationView
        if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
        {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            let imageView = UIImageView(frame: CGRectMake(0, 0, 45, 45))
            imageView.image = UIImage(named:"picture")
            imageView.layer.cornerRadius = imageView.layer.frame.size.width / 2

            imageView.layer.borderWidth = 1.5
            imageView.layer.borderColor = UIColor(red: 230/255, green: 39/255, blue: 39/255, alpha: 1).CGColor
            imageView.layer.masksToBounds = true
            view.addSubview(imageView)

            view.canShowCallout = true
            view.calloutOffset = CGPoint(x:  16, y: 16)
            view.layer.anchorPoint = CGPointMake(16 , 16)
            view.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as! UIView
        }
        return view
    }
    return nil
}
}

image

image

1 个答案:

答案 0 :(得分:0)

使用子视图实现cornerRadius和callOut时,我设法通过乱搞anchorPoint来对齐图像和触摸区域。唯一的问题是触摸半径与原始MKAnnotationPin的触摸半径类似,因此用户必须准确了解要点击的位置。否则,最好的方法(也是最乏味的)是子类化MKAnnotationView并覆盖drawRect方法以为图像绘制圆形蒙版。为了让生活更轻松,我找到了一个名为Toucans的库来实现这种功能。

imageView.layer.anchorPoint = CGPoint(x: 1, y: 1)