【问题标题】:Resize annotationview frame to custom shape将注释视图框架调整为自定义形状
【发布时间】:2022-01-16 21:11:26
【问题描述】:

我正在开发一个在地图上使用自定义 annotationview 引脚的应用程序。 pin的头部是一个动态调整大小的按钮。我对 swift 很陌生,并注意到该按钮仅在位于 annotationviews 框架的顶部时才会注册,因此我将框架设置为足够大以始终包含 uibutton。

问题:当我在地图上有多个大头针时,大框架会与其他大头针重叠并干扰点击它们。我想让框架尽可能小,这样它就不会干扰敲击其他引脚。 框架当然可以通过缩小框架矩形来缩小,但我想知道我是否可以做得更好。

我的问题是:有没有办法修改注释视图的框架形状,使其与图钉的形状相同,而不是矩形?

  • 我想使用 bezierpaths 来实现这一点,但无法弄清楚如何

Here is an image of the custom pin

-蓝色是框架,红色是贝塞尔路径,我试图将其设置为框架,但只是被绘制了

【问题讨论】:

    标签: ios swift frame uibezierpath mkannotationview


    【解决方案1】:

    我测试了自定义尺寸按钮,只有点击绿色部分才会触发。

    class TestButton: UIButton {
        var path:UIBezierPath!
        var drawLayer:CAShapeLayer!
        
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func draw(_ rect: CGRect) {
            path = UIBezierPath()
            path.move(to: CGPoint(x: 60, y: 100))
            path.addLine(to: CGPoint(x: 0, y: 100))
            path.addArc(withCenter: CGPoint(x: 100, y: 100), radius: 100, startAngle: .pi, endAngle: .pi*1.5, clockwise: true)
            path.addLine(to: CGPoint(x: 100, y: 60))
            path.addArc(withCenter: CGPoint(x: 100, y: 100), radius: 40, startAngle: .pi*1.5, endAngle: .pi, clockwise: false)
            path.close()
            
            drawLayer = CAShapeLayer.init()
            drawLayer.path = self.path.cgPath
            drawLayer.fillColor = UIColor.green.cgColor
            self.layer.addSublayer(self.drawLayer)
        }
        
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            if self.path.contains(point) {
                return true
            } else {
                return false
            }
        }
        
        public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            print(point)
            let tmp=super.hitTest(point, with: event)
            print(tmp)
            return tmp
        }
    }
    
    
    class vc_UnitTest: UIViewController {
    
        @IBAction func openLoginHome(_ sender: Any) {
            let bbb = TestButton.init(frame: CGRect.init(x: 50, y: 400, width: 150, height: 150))
            bbb.backgroundColor = .red
            self.view.addSubview(bbb)
        }
    }
    

    【讨论】:

    • 问题不是按钮的形状,而是按钮周围的annotationview框架干扰了其他按钮。这并不能解决我的问题,但我感谢您的帮助。另外,到目前为止,我主要通过缩小框架直到它基本适合内容来解决我的问题
    • 这是一个例子,你可以使用这个函数来自定义你的annotationview框架。如:类TestAnnotationview:UIView {}
    • 好的,谢谢,我会试一试
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多