首页 > 解决方案 > 使用 SwiftUI 或 UIKit 定位视图元素?

问题描述

这或多或少是对一个我认为可以被复制得更少的问题的重新发布。我正在尝试使用覆盖的 draw() 函数和标注的其余部分创建的三角形来形成文本气泡。我删除了所有不可能影响三角形或盒子定位的代码。

回顾:我想将绘制函数创建的三角形移动到初始化中创建的框架之外(目前,它在框架内)。

如果我可以添加任何内容来澄清或使这个问题变得更好,请告诉我。

class CustomCalloutView: UIView, MGLCalloutView {

    let dismissesAutomatically: Bool = false
    let isAnchoredToAnnotation: Bool = true
    let tipHeight: CGFloat = 10.0
    let tipWidth: CGFloat = 20.0
    lazy var leftAccessoryView = UIView()
    lazy var rightAccessoryView = UIView()

    weak var delegate: MGLCalloutViewDelegate?

    //MARK: Subviews -



    required init() {
        // init with 75% of width and 120px tall
        super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 
        UIScreen.main.bounds.width * 0.75, height: 120)))

        setup()
    }

    override var center: CGPoint {
        set {
            var newCenter = newValue
            newCenter.y -= bounds.midY
            super.center = newCenter
        }
        get {
            return super.center
        }
    }

    func setup() {
        // setup this view's properties
        self.backgroundColor = UIColor.white
}


func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, 
animated: Bool) {
    //Always, Slightly above center
    self.center = view.center.applying(CGAffineTransform(translationX: 0, y: -self.frame.height))
    view.addSubview(self)

}


override func draw(_ rect: CGRect) {

    // Draw the pointed tip at the bottom.
    let fillColor: UIColor = .black

    let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0)
    let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0), y: rect.origin.y + 
    rect.size.height)
    let heightWithoutTip = rect.size.height - tipHeight - 1

    let currentContext = UIGraphicsGetCurrentContext()!

    let tipPath = CGMutablePath()
    tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip))
    tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y))
    tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip))
    tipPath.closeSubpath()

    fillColor.setFill()
    currentContext.addPath(tipPath)
    currentContext.fillPath()
}
}

标签: swiftviewswiftui

解决方案


推荐阅读