UIView的中心点似乎不准确

时间:2018-12-17 17:37:45

标签: swift uiview uikit xib centering

我有一个自定义UIView,我是从xib加载的,其中包含一些内容,例如标签和图像以及其他视图。我将此视图放置在情节提要中UIViewController的根视图内。添加约束等。看起来很棒。

然后我要创建另一个看起来像气泡的自定义UIView,它将使用类函数从UIViewController进行调用。通过此功能,我想将该视图的语音气泡点放置在基础视图的中心。因此,我相信我们需要使用UIView的convert(_:to:)方法在视图控制器的视图上下文中为基础视图的中心点提供参考。这应该将坐标返回到基础视图的中心,但要参考整个屏幕而不是视图本身。

使用此功能的CGRect版时获得的结果似乎是准确的。但是,当我使用CGPoint来获取该视图的中心点时,它似乎已经偏离了。检查一下:

Depicts the main view as well as the underlying viewsframed by colored borders, along with dots that represent the coordinates to the center of the underlying view

这是我正在使用的代码:

class TipView: UIView {
    class func present(overView targetView: UIView, _ vc: UIViewController, outlineColor: UIColor) {
        //frame the underlying view
        let viewFrame = targetView.convert(targetView.bounds, to: vc.view)
        let frameView = UIView(frame: viewFrame)
            frameView.backgroundColor = .clear
            frameView.layer.borderColor = outlineColor.cgColor
            frameView.layer.borderWidth = 5

        vc.view.addSubview(frameView)

        //place a dot at the center of the underlying view
        let targetViewCenter = targetView.convert(targetView.center, to: vc.view)
            targetView.dot(atPoint: targetViewCenter, color: outlineColor)
    }
}


extension UIView {
    func dot(atPoint point: CGPoint, size: CGSize = CGSize(width: 8, height: 8), color: UIColor = .black) {
        let dotPath = UIBezierPath(ovalIn: CGRect(origin: CGPoint(x: center.x - size.width/2,
                                                              y: center.y - size.height/2),
                                              size: size))
        let layer = CAShapeLayer()
            layer.path = dotPath.cgPath
            layer.strokeColor = color.cgColor
        self.layer.addSublayer(layer)
    }
}
class ViewController: UIViewController {
    @IBOutlet weak var HUDView: HUDView!

    @IBAction func toggleTipView(_ sender: UIButton) {
        let targetView = HUDView.graySquare!
        TipView.present(overView: targetView, self, outlineColor: .green)

        let targetView2 = HUDView.HPBar!
        TipView.present(overView: targetView2, self, outlineColor: .blue)
    }
}

class HUDView: UIView {
    @IBOutlet weak var graySquare: UIView!
    @IBOutlet weak var HPBar: UIView!
}

我对这里发生的事情有些困惑。有什么想法吗?

0 个答案:

没有答案